_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d15101 | val | Combining html/xml with regular expressions has a tendency to turn bad.
Why not use bs4 to find the 'a' elements in the div you're interested in and get the 'href' attribute from the element.
see also retrieve links from web page using python and BeautifulSoup | unknown | |
d15102 | val | You have to replace the mvRoot.get(MonitoringBE.id_travel) and others in the multiselect-statement with mvRoot.join(MonitoringBE.id_travel, JoinType.LEFT). Otherwise they will end up in a inner join. | unknown | |
d15103 | val | Fetching data to the client and returning row by row back to the server
can well produce big overhead. There's better way to do the same,
so called "insert/select" query:
using (SqlCommand command = connection.CreateCommand()) {
command.CommandText =
"insert into Flight_Reservation(\n" +
" Customer_Id,\n" +
" Tariff_Id,\n" +
" Total_Price)\n" +
" select Customer_Id,\n" +
" @prm_Tariff_Id,\n" +
" @prm_Total_Price\n" +
" from Customer\n" +
" where (UserName = @prm_UserName)\n" +
" (Password = @prm_Password)";
command.Parameters.Add("@prm_Tariff_Id", SqlDbType.VarChar, 80).Value = tariff_id;
command.Parameters.Add("@prm_Total_Price", SqlDbType.VarChar, 80).Value = total_price.ToString();
command.Parameters.Add("@prm_UserName", SqlDbType.VarChar, 80).Value = username;
command.Parameters.Add("@prm_Password", SqlDbType.VarChar, 80).Value = password;
command.ExecuteNonQuery();
} | unknown | |
d15104 | val | //First, set up `rectangles` as an array containing two arrays.
var rectangles = [];
rectangles[0] = [];
rectangles[1] = [];
//As `google.maps.Rectangle` doesn't accept a `url` option,
//its url needs to be defined separately from the rectangle itself,
//but in such a way that the two are associated with each other.
//For this we can use a javascript plain object.
rectangles[0][0] = {
rect: new google.maps.Rectangle({
bounds: new google.maps.LatLngBounds(new google.maps.LatLng(a, b), new google.maps.LatLng(x, y)),
map: map,
fillColor: 'red',
fillOpacity: 0.3,
strokeOpacity: 0,
clickable: true
}),
url: 'http://example.com'
};
rectangles[1][0] = new google.maps.Rectangle({
...
});
rectangles[0][1] = new google.maps.Rectangle({
...
});
rectangles[1][1] = new google.maps.Rectangle({
...
});
rectangles[0][2] = new google.maps.Rectangle({
...
});
rectangles[1][2] = new google.maps.Rectangle({
...
});
//Now to attach the click listeners.
//First we define a function that adds a click listener.
//By doing this in its own function, a closure is formed,
//trapping the formal variable `rectObj` and making `rectObj.url`
//accessible to the listener when it is called in response to future clicks.
function addClickListener(rectObj) {
google.maps.event.addListener(rectObj.rect, 'click', function() {
window.location.href = rectObj.url;
});
}
//Now, we can loop through the `rectangles` arrays, adding listeners.
for ( i = 0; i < 2; i++ ) {
for ( j = 0; j < 14; j++ ) {
if(rectangles[i][j]) {//safety
addClickListener(rectangles[i][j]);
}
}
} | unknown | |
d15105 | val | You should ensure that you have a JS runtime declared in your Gemfile.
Try adding:
gem 'therubyracer'
or
gem 'execjs'
to your Gemfile and run:
bundle install
A: As mentioned above you need a JavaScript runtime. If you are unsure of which to choose, I've always been told to use Node.js | unknown | |
d15106 | val | Do aggregation using GROUP BY clause :
SELECT Deadline, COUNT(*) AS [# computers delivered]
FROM Inventory
GROUP BY Deadline;
DISTINCT will remove duplicate values so, that will not help you.
A: Presumably, deadline is the delivery date. If so, you want aggregation:
SELECT Deadline, COUNT(*)
FROM Inventory
GROUP BY Deadline
ORDER BY Deadline | unknown | |
d15107 | val | I was able to figure out the problem. The problem was with the package version of DT on the server. The package version of DT on the server was 0.1 and that version has some bugs (based on this post: https://github.com/rstudio/DT/issues/206)
I was able to get the package version updated to 0.2 and all worked fine.
The problem was with using input$table_rows_selected with the old version of DT package with selection = 'single' as a parameter. Moving to 0.2 version of DT package resolved the problem. | unknown | |
d15108 | val | I had a similar issue but with a different combination of keys. I found that i had to split the action into 3 steps: Ctrl+alt+ "letter", then Ctrl+alt, then all buttons released. So just looking at your code, maybe try sending this sequence:
0xFD,0x09,0x01,0x05,0x00,0x0B,0x00,0x00,0x00,0x00,0x00 //ctrl + alt + h
0xFD,0x09,0x01,0x05,0x00,0x00,0x00,0x00,0x00,0x00,0x00 //ctrl + alt
0xFD,0x09,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 //all released.
A: I'm not sure of a raw report, but I did manage it with [0xFD,0x03,0x03,0x01,0x00] (down), and [0xFD,0x03,0x03,0x00,0x00] (up) | unknown | |
d15109 | val | The only way to dynamically access variables is if they're in a temp-table. local variables cannot be accessed dynamically. | unknown | |
d15110 | val | Modify your callback def to:
def callback(event=None):
print(button_name)
This is because the callback that tkinter calls is actually the callback function, not the test function. Test function does not need event=None. | unknown | |
d15111 | val | Expand the "this" item on Variables view; it contains variable val$x where you can see the x and it's value. | unknown | |
d15112 | val | You have to work with the data set, not with the adapter.
e.g: If you fill a ListView with a ArrayList<T> object, if you want to delete a row in the list you have to delete it from the ArrayList and then call the notifyDataSetChanged().
// ArrayList<T> items filled with data
// delete the item that you want
items.remove(position);
// so, communicate to the adapter that the dataset is changed
adapter.notifyDataSetChanged();
In your specific case, the item from materialsModel, then notufy it to the adapter, something like follwing:
// remove the item
// I don't know which method you must call, hope you do ;)
materialsModel.remove(position)
// then notify the adapter that the dataset is changed
adapter.notifyDataSetChanged();
A: try the following code:
materialsListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Resources r = getResources();
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
int pxTop = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 6, r.getDisplayMetrics());
AlertDialog.Builder alertDialog = new AlertDialog.Builder(QuoteDetailActivity.this);
alertDialog.setTitle("Delete.");
alertDialog.setPositiveButton("Yes", (dialog, which) -> {
LinkedTreeMap<String, Object> selectedItem = adapter.getItem(position);
int QuoteMaterialId = ((Double) selectedItem.get("QuoteMaterialId")).intValue();
viewModel.deleteMaterial(quoteId,QuoteMaterialId);
adapter.remove(selectedItem);
adapter.notifyDataSetChanged();
//adapter.remove(adapter.getItem(position));
//adapter.notifyDataSetChanged();
});
alertDialog.setNegativeButton("No", (dialog, which) -> {
dialog.dismiss();
});
alertDialog.show();
return true; }
});
A: Either use a different constructor with list items in MyArrayAdapter
public MyArrayAdapter(Context context, int resource, List<T> objects) {
super(context, resource, objects);
}
or override the remove method of the adapter and manually delete the items
@Override
public void remove(T object) {
items.remove(object);
} | unknown | |
d15113 | val | I always use the string value. I see absolutely no benefit in using the constants. The chance of them changing is virtually zero. These constants have remained unchanged since Tkinter was created.
tkinter takes backwards compatibility pretty seriously, so even if they are changed, the string values will undoubtedly continue to work for a year or two.
My recommendation is to never use the constants.
A: This is done mostly for user convinience.
Consider the Image class from PIL/Pillow. It has a method to create a thumbnail out of an image, in the process resizing it. The method takes two arguments, the new size in a tuple and a resampling method. This can be antialias, bilinear, cubic, etc. These are internally represented with integer values, like 0, 1, etc. If you don't know which value represents which resampling method, it's cumbersome to look it and may also lead to more errors. But access it from the constant Image.BILINEAR and boom, you're done.
In your case, importing W just for the string "w" seems to be needlessly polluting the namespace and typing tkinter.W is longer than "w". This might be so. However, remember, constants in a program are defined in one place so if you ever have to change them, it will be easy to so. You never know, the module may be internally use the constant W, even if you see no point in it.
This also leads to the reason you pointed out. A constant may have a different value depending on the system or version. By using the internally consistent constant and not a static, hardcoded value, you make your life easier when you reuse that code on a diferent system or version. | unknown | |
d15114 | val | Running include inside ob_start and ob_get_clean did the trick
function jsd_waitlist_hero_shortcode() {
ob_start();
include dirname( __FILE__ ) . '/jsd-templates/' . 'jsd-waitlist-hero.php';
$content = ob_get_clean();
return $content;
} | unknown | |
d15115 | val | Yes, this can be accomplished with layouts, spacers and size policies. Here is a screen shot from QtCreator that reproduces the effect you are looking for:
The "TopWidget" will occupy as little space as necessary as dictated by the widgets it contains and the "BottomWidget" will expand to occupy all remaining space when the application window is resized.
The "BottomWidget" has both horizontal and vertical size policies set to "expanding".
A: I figured out how to do it : it is enough to set the stretch factors.
In the above example :
for ( LayoutDefinition::const_iterator it = newLayoutDef.begin(); newLayoutDef.end() != it; ++ it )
{
QWidget * w( containers.at( it->item ) );
newLayout->addWidget( w, it->row, it->column );
w->show();
}
newLayout->setRowStretch( 0, 1 );
newLayout->setRowStretch( 1, 2 );
This will cause the 2nd row to be two times bigger then the 1st row.
A: It's impossible. Layout is a thingy that is supposed to automatically manage layout and size of widgets. Write your own layout. | unknown | |
d15116 | val | To get access to signal handling you have to use sun's private classes, which makes your code not portable any mode. Anyway...
import sun.misc.Signal;
public static void main(String[] args) {
registerSignalHandler();
}
@SuppressWarnings("restriction")
private static void registerSignalHandler() {
Signal.handle(new Signal("HUP"), (Signal signal) -> {
System.out.println("Hello signal!");
});
} | unknown | |
d15117 | val | I found that the command cannot update the .ipynb that was already created under an old version of R.
But the Jupiter environment did provide the new version after the command line IRkernel::installspec(name = 'ir35', displayname = 'R 4.0.0').
It can be used when adding a new Notebook as the following pic. shows: | unknown | |
d15118 | val | I see a bunch of related issues on leaflet's github. The maintainer seems to have something against frameworks.
Check out https://react-leaflet.js.org/ that should work better with react. | unknown | |
d15119 | val | The function that is exported from that Delphi DLL cannot be called from C#. The Delphi DLL exports the function using the register calling convention which is a non-standard Delphi only calling convention. You will need to modify the DLL to export using, for instance, stdcall.
Assuming you made the change the C# code would look like this:
[DllImport("patch.dll")]
static extern void DoPatch(IntPtr moduleHandle);
....
IntPtr OcxHandle = LoadLibrary("SampleOcx.dll");
if (OcxHandle == IntPtr.Zero)
.... handle error
DoPatch(OcxHandle);
Note that the parameter is not really a DWORD. It is an HMODULE. That's a 64 bit type under 64 bit process. Which leads me to point out that your program must target x86 to work with your 32 bit Delphi DLL. And the OCX is presumably 32 bits too. | unknown | |
d15120 | val | You haven't implemented the init(coder:) initialiser, as you can see here:
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
You seem to be loading some cells from the storyboard, so you must not just use fatalError here.
The implementation should be quite simple. You can just do the same thing as what you do in the init(frame:) initialiser:
class MasterViewCell: UICollectionViewCell {
let customView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 12
return view
}()
var cellImageView: UIImageView!
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
self.addSubview(self.customView)
self.customView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
self.customView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
self.customView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 1).isActive = true
self.customView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 1).isActive = true
}
} | unknown | |
d15121 | val | It is a LLVM intrinsic function. As per the language reference:
LLVM provides intrinsics for a few important standard C library
functions. These intrinsics allow source-language front-ends to pass
information about the alignment of the pointer arguments to the code
generator, providing opportunity for more efficient code generation.
The llvm.memcpy intrinsic specifically:
The ‘llvm.memcpy.*’ intrinsics copy a block of memory from the source
location to the destination location.
Note that, unlike the standard libc function, the llvm.memcpy.*
intrinsics do not return a value, takes extra isvolatile arguments and
the pointers can be in specified address spaces. | unknown | |
d15122 | val | else (num > 100)
should be
else if (num > 100)
else clause doesn't any condition - it's just a syntax error.
You should also check if scanf() call succeeded:
if (scanf("%f", &num) != 1) {
printf("Input error");
exit(1);
}
A: else does not take an expression, it is associated with the lexically nearest preceding if that is allowed by the syntax.
The format is
if ( expression ) statement else statement
Quoting C11, chapter §6.8.4.1
[...] the first substatement is executed if the expression compares unequal to 0.
In the else form, the second substatement is executed if the expression compares equal to 0. If the first substatement is reached via a label, the second substatement is not
executed.
So, to check for another condition, you need to have another if clause.
Compile your code with warnings enabled and you'll get to see a compiler screaming like
warning: statement with no effect [-Wunused-value]
else (num > 100)
^ | unknown | |
d15123 | val | Here's a simple workaround which might help until a better solution comes up. It returns a list of all public symbols defined in a file. Let's read the file and look for all def sexps. Ignore private ones, i.e. ones like defn-.
(let [file (with-in-str (str "(" (slurp filename) ")") (read))
defs (filter #(.matches (str (first %)) "^def.*[^-]$") file)
symbols (map second defs)]
symbols)
Caveats:
*
*Well, it's simply naïve.
*It doesn't get rid of all private definitions. Ones defined with ^{:private true} or ^:private are not filtered out.
*Definitions can be generated using macros.
The last point is especially troubling. The only reasonable way to detect definitions generated with macros is to evaluate the file with the reader, at least partially.
A: Parsing isn't going to work because clojure is very dynamic.
So, something like this might work...
(load-file "file_with_stuff.clj")
(ns-publics (find-ns 'file-with-stuff))
(remove-ns 'file-with-stuff)
If you want to do everything dynamically, then you can generate the symbols using symbol -- should still work. Removing the ns is optional. It won't do any harm, but it does put you back where you started. | unknown | |
d15124 | val | Yes, there is an method for revoking of Google Drive scope.
GoogleSignInClient googleSignInClient = buildGoogleSignInClient();
googleSignInClient.revokeAccess().addOnCompleteListener(onCompleteListener);
where
private GoogleSignInClient buildGoogleSignInClient() {
GoogleSignInOptions signInOptions =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.build();
return GoogleSignIn.getClient(this, signInOptions);
}
For more information, you can check this reference | unknown | |
d15125 | val | I think you had a typo.
It should work if you set interval = 0 (not "interval = 0s")
After that change you must restart the icinga service. | unknown | |
d15126 | val | You can use RabbitMQ .It's easy to use and also support huge number of developer platform. | unknown | |
d15127 | val | Turns out I am fully capable of writing to the external storage directory on a real smartphone device (Huawei P8 api level 21, Version 5.0). But not to the emulator's external storage, even though the storage is fully available and can be browsed from within the emulator.
This also helped me in figuring out issues with the external storage on a real device: https://stackoverflow.com/a/6311955/5330055
I have no longer urgently require a solution on this, but it would be nice to know what is wrong with the emulator.
A: Actually nothing wrong with emulator.
Probably device you have used on emulator were on android equal or higher than version 6.0
In 6.0 and higher versions you need to request write permission at runtime. WRITE_EXTERNAL_STORAGE
in your smartphone it worked because it was on android 5.0
if this help someone I will glad. | unknown | |
d15128 | val | Hide the first tabbed page's navigation bar via:
var maintTabNav = new FreshTabbedFONavigationContainer("Aerogrow", NavigationContainerNames.MainContainer);
maintTabNav.FirstTabbedPage.On<Xamarin.Forms.PlatformConfiguration.Android>().SetToolbarPlacement(ToolbarPlacement.Bottom);
NavigationPage.SetHasNavigationBar(maintTabNav.FirstTabbedPage, false);
If you don't want to see the navigation bar on each page make your page inherit from a base page. Then set the property in the base page:
public class BasePage : ContentPage
{
public BasePage()
{
NavigationPage.SetHasNavigationBar(this, false);
}
} | unknown | |
d15129 | val | Not sure and I have enough element to try but... what about checking persistence (the template parameter of serialize_custom()) instead of customPersistence (that isn't a template parameter of serialize_custom()?
I mean... what about as follows?
template <class Archive, class Base,
decltype(customPersistence) & persistence = customPersistence>
std::enable_if_t<std::is_base_of<cereal::InputArchive<Archive>, Archive>::value
&& has_deserialize<std::remove_const<decltype(persistence)>::type,
Archive&, Base&>() == true> //^^^^^^^^^^^
serialize_custom(Archive &ar)
{
persistence.deserialize(ar, const_cast<Base&>(*this));
}
A: I finally solved this problem with an intermediary method (in case anyone is interested):
template <class Archive>
void serialize(Archive& ar)
{
serialize_custom_helper(ar);
}
template <class Archive, decltype(customPersistence)& persistence = customPersistence> \
void serialize_custom_helper(Archive& ar)
{
serialize_custom(ar, persistence);
}
template <class Archive, class Base, class P>
std::enable_if_t<std::is_base_of<cereal::InputArchive<Archive>, Archive>::value && has_deserialize2<P, Archive&, Base&>() == true, void>
serialize_custom(Archive &ar, P& persistence)
{
persistence.deserialize(ar, const_cast<Base&>(*this));
}
... | unknown | |
d15130 | val | Solution: This can be done without VBA if you can add the county name for each entry. Let's say, you are putting them into column J (see yellow cells in below picture).
Then, to count totals, simply use the COUNTIF function to get the total number of rows for a county and substract those who are marked "X" using the COUNTIFS function. In cell N2, I entered:
=COUNTIF(J:J,L2)-COUNTIFS(J:J,L2,H:H,"X")
Add the other county names below the existing ones in column L and copy the formula from N2 to the cells below.
Explanation: COUNTIF counts the number of rows that match one criterion. Here, we are setting the county name (L2 for the first county) and we are looking for it in column J. Next, we need the number of rows that match both the county and the completion state of "X". COUNTIFS will do the trick as it counts the number of rows that match two or more criteria. In this case, we want the number of rows of a given county (column J) and we want them to be the value of a value in column L ("Bronx" for N2, "Manhattan" for N3 etc.). The second criterion is their completion state (column H) which you want to be X (specified in the formula as "X"). You then substract the second from the first number.
Edit: By the way, sorting does not affect these formulas, they will continue to work. | unknown | |
d15131 | val | You can split it up into an array, and make each left side into a regexp.
then you can run a guantlet of tests to find the match.
the tricky part is that you need to make multiple tests, beyond just one super regexp. i used [].some() to terminate after the first match is found. you can change the some with filter and collect the output to get multiple matches.
var gaunlet=[],
str="[Database.txt]\n\
Hello*==Hello. How are you?\n\
How*are*you*==I am fine I guess.\n\
Can you*die*==I can not die. I am software.";
str.split("\n").forEach(function(a,b){
var r=a.split("==");
gaunlet[b]=[RegExp(r[0].replace(/\*/g,"[\\w\\W]*?"), "i"), r[1]];
});
function lookup(inp){
var out;
gaunlet.some(function(a){
if(a[0].test(inp)) return out=a[1];
});
return out;
}
alert(lookup("can you die in a million years?"));
fiddle: https://jsfiddle.net/joaze5u6/1/
i also wrote in a fix for the way js captures wildcards, the [\w\W]*? does what .*? should probably do but doesn't in js... | unknown | |
d15132 | val | You can use the iTunes Search API: http://www.apple.com/itunes/affiliates/resources/documentation/itunes-store-web-service-search-api.html
This page can help you better understand how the iTunes Search API works: http://www.phponwebsites.com/2015/03/get-app-details-from-apple-itunes-using-php.html | unknown | |
d15133 | val | In the solution's properties, under Common Properties, Startup Project, you can choose Multiple startup projects and select Start as the action for both the service and the consumer. | unknown | |
d15134 | val | In fact you don't need to check existence. You should only do:
foreach ($model->hasManyRelationFunction as $elem) {
// do whathever you want
}
and it's just enough to get the data. You don't need to check existence here or if you think you do, you should show a real example of a code what you are trying to achieve. | unknown | |
d15135 | val | These compile to nearly identical code.
The first syntax translates directly, by the compiler, into methods with the names provided in the second syntax.
The main difference between these two methods is really just that you're using a different syntax, and that you're assigning to a temporary variable (query) instead of just returning the result directly. However, they are, for all practical purposes, identical. | unknown | |
d15136 | val | How about this instead?
create view fg_voted as (
SELECT f1.foto,
count(f1.vote) stars,
f1.vote,
f1.voted
FROM fg_foto_bewertung f1
WHERE f1.vote >= 3
GROUP BY f1.foto,
f1.vote,
f1.voted
HAVING count(f1.vote) > 3
); | unknown | |
d15137 | val | In my experience, this is caused by the pager() method of Backbone.Paginator.clientPager. You can take a look at the code here:
Backbone.Paginator.clientPager
Lines 292 through to 294 show that the Backbone.Paginator.clientPager.origModels is only assigned to the current models (the one whose length you correctly tested in your illustrations above) if it's undefined. The problem is that by the time the user probably wants to load more pages without deleting the first, the origModels property would already be set as a result of the initial fetch.
This means you'd have to explicitly make origModels undefined again before pager() would act as you want. Note what happens later on line 296 of the source code (models is assigned to a copy of origModels). That's why your two new records were removed. The following code should work as you intended:
myCollection.currentPage = 2;
myCollection.fetch({
success: function(){
delete myCollection.origModels; // to ensure that origModels is overridden in pager() call below
myCollection.pager();
},
silent:true,
remove: false // don't remove old records
}); | unknown | |
d15138 | val | It's currently not possible to have more than one docker tag name by build. Duplicating the build is the only solution.
A: You can use the tags regexp
Look at the last tag that gets created. | unknown | |
d15139 | val | If you're using Linux docker hosts, you could try using the host network mode. | unknown | |
d15140 | val | Interesting point to consider, I tried it both ways and essentially both approaches lead to the same result.
I would say both approaches are equivalent in the simplest example.
If you look at the CSS specification, the left/right offsets and the left/right margins and the width can be constrained depending on which values are specified or set to auto.
See: http://www.w3.org/TR/CSS21/visudet.html#abs-non-replaced-width
However, I found it hard to imagine a case in which specifying offsets versus margins would make a difference (there might be an exotic case, but I can't think of it off the top of my head).
body {
margin: 0;
}
.popup {
background-color: yellow;
position: fixed;
right: 0;
bottom: 0;
margin: 40px;
}
.popup-alt {
background-color: lightblue;
position: fixed;
right: 40px;
bottom: 40px;
}
<div class="popup">Yellow Popup Element</div>
<div class="popup-alt">Blue Popup Element</div> | unknown | |
d15141 | val | If you're upgrading jQuery, then also upgrade to the latest jQuery UI where slider setup is much easier:
$(".slider").slider();
EDIT:
Working example, using latest jQuery and jQuery UI: Fiddle
Full-screen link: here | unknown | |
d15142 | val | The last part will be potentially smaller or larger than size_of_part, as the original file size is not a multiple of it.
You need to adapt the size of the last part automatically.
For instance, if you have a file size of 1000 bytes, and 7 parts.
Your computed file size will be 142. 7*142 = 994, you are missing the last 6 bytes. Is this your problem?
The fseek is not required, why are you using it? You just need to read the input file sequentially
void split_F(const char* file_name, int number_of_part)
{
FILE *fp_read = fopen(file_name, "rb");
//calculate file size
int file_size;
fseek(fp_read, 0L, SEEK_END);
file_size = ftell(fp_read);
rewind(fp_read); //reset file pointer
//calculate number of parts
long size_of_part;
size_of_part = (int)ceil((double)file_size / number_of_part);
cout << "Total files after split: " << number_of_part << endl
<< "...Processing..." << endl;
//main process
char name[255] = "";
int bytesRemaining = file_size;
//create buffer, we reuse it for each part
char *buffer = new char[size_of_part];
//No need to reset buffer
//memset(buffer, NULL, partSize);
for (int count = 1; count <= number_of_part; count++)
{
sprintf(name, "%s.part_%03d", file_name, count);
FILE *fp_write = fopen(name, "wb");
int partSize;
if(bytesRemaining > size_of_part)
{
partSize = size_of_part;
}
else
{
partSize = bytesRemaining;
}
fread(buffer, partSize, 1, fp_read);
fwrite(buffer, partSize, 1, fp_write);
cout << "> File: " << name << " done babe!" << endl;
fclose(fp_write);
}
fclose(fp_read);
delete[] buffer;
}
A: You are calculating size_of_part as a rounded quotient of file size and the requested number of parts. You then proceed to read the file in chunks of that exact size. This will fail unless the file size is a multiple of number_of_parts. You need to fix your code to allow the last part to be smaller than size_of_part.
A: Your file may not divide into N parts of equal lengths (suppose the file is 7 bytes long and you divide it into 3 parts...?)
long remaining_size = file_size;
long size_of_part;
size_of_part = (file_size + number_of_part - 1) / number_of_part;
This makes the part length rounded up, so possibly the last part will be shorter than all preceding parts.
//create buffer
char *buffer = new char[size_of_part];
//main process
char name[255] = "";
for (int count = 1; count <= number_of_part; count++)
{
sprintf(name, "%s.part_%03d", file_name, count);
FILE *fp_write = fopen(name, "wb");
long this_part_size =
remaining_size < size_of_part ? remaining_size : size_of_part;
fread(buffer, this_part_size, 1, fp_read);
fwrite(buffer, this_part_size, 1, fp_write);
cout << "> File: " << name << " done babe!" << endl;
fclose(fp_write);
remaining_size -= this_part_size;
}
delete[] buffer; | unknown | |
d15143 | val | I assume it supposed to hold some maximum number of objects and then dispose the extra. I read book's description like 10 times.. and couldn't get it. Maybe someone explain how this works?
Sort of. The class keeps a cache of pre-created objects in a List called pool. When you ask for a new object (via the newObject method) it will first check the pool to see if an object is available for use. If the pool is empty, it just creates an object and returns it to you. If there is an object available, it removes the last element in the pool and returns it to you.
Annotated:
if (freeObjects.isEmpty()) {
// The pool is empty, create a new object.
object = factory.createObject();
} else {
// The pool is non-empty, retrieve an object from the pool and return it.
object = freeObjects.remove(freeObjects.size() - 1);
}
And when you return an object to the cache (via the free() method), it will only be placed back into the pool if the maximum size of the pool has not been met.
Annotated:
public void free(T object) {
// If the pool is not already at its maximum size.
if (freeObjects.size() < maxSize) {
// Then put the object into the pool.
freeObjects.add(object);
}
// Otherwise, just ignore this call and let the object go out of scope.
}
If the pool's max size has already been reached, the object you are freeing is not stored and is (presumably) subject to garbage collection.
A: The idea of any pool is in creating controlled environment where (usually) no need to create new (event) instances when some unused free instances can be re-used from the pool.
When you create
touchEventPool = new Pool<TouchEvent>(factory, 100);
you hope 100 instances will be enough in any particular moment of the program live.
So when you want to get 101'st event the process probably will free first 5, 20 or even 99 events and the pool will be able to reuse any of them.
If there will be no free instances then depending on the pool policy the new one will be created or the requestor thread will wait other threads to release one and return to the pool. In this particular implementation the new one will be created.
A: I think that the main concept of object pool is to reduce frequency of object instanciations.
Does this mean it is going to store an Array of 100 events (and when #101 comes inside, will dispose #1, like first-in-first-out)?Does this mean it is going to store an Array of 100 events (and when #101 comes inside, will dispose #1, like first-in-first-out)?
I don't think so. The maximum number 100 means that of freeObjects but of currently using objects. When an object is not used any more, you shall free it. Then the freed object won't be descarded but be stocked as a freeObject (the max num means that of these spared objects). Next time you need another new object, you don't have to instanciate a new object. All you need is just reusing one of spared freeObjects.
Thus you can avoid costly object instanciations. It can improve in performance. | unknown | |
d15144 | val | Setting IsEnabled to false prevents the Map control from responding to user input, which affects the child Pushpin as you've seen. If you want the map to be read-only but the Pushpin to respond to gestures then I think you have two options:
*
*Handle all the gesture events on the Map control and set e.Handled to true, which will prevent the Map itself from processing the event, but should leave the PushPin free to handle the tap gesture.
*Create a WriteableBitmap of the Map and show that instead, and then display the Pushpin on top (NOTE: I suspect that the Pushpin control won't work outside of the Map control, so you'd need to create/re-template a control to look like a Pushpin).
UPDATE: The events that you need to handle on the Map to make it appear "read-only" but remain enabled are MapPan and MapZoom.
A: So here's how I solved it after a lot of testing and browsing MSDN. It turns out that things are a bit different in the Map control on Windows Phone (see MSDN). There are new behaviors and events compared to normal Silverlight.
<maps:Map Name="Map"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
CopyrightVisibility="Collapsed" LogoVisibility="Collapsed" ScaleVisibility="Collapsed" ZoomBarVisibility="Collapsed"
MapZoom="Map_MapZoom" MapPan="Map_MapPan">
<maps:MapItemsControl ItemsSource="{Binding TheCollection}">
<maps:MapItemsControl.ItemTemplate>
<DataTemplate>
<maps:Pushpin Name="Pin" Location="{Binding Coordinate}" Content="{Binding Ix}">
<maps:Pushpin.Background>
<SolidColorBrush Color="{StaticResource PhoneAccentColor}"/>
</maps:Pushpin.Background>
<toolkit:GestureService.GestureListener>
<toolkit:GestureListener Tap="PinTap" />
</toolkit:GestureService.GestureListener>
</maps:Pushpin>
</DataTemplate>
</maps:MapItemsControl.ItemTemplate>
</maps:MapItemsControl>
</maps:Map>
...
private void Map_MapPan(object sender, MapDragEventArgs e)
{
e.Handled = true;
}
private void Map_MapZoom(object sender, MapZoomEventArgs e)
{
e.Handled = true;
} | unknown | |
d15145 | val | Try this:
def print_slow(str):
for letter in str:
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(0.1)
print_slow("Type whatever you want here")
A: This is my "type like a real person" function:
import sys,time,random
typing_speed = 50 #wpm
def slow_type(t):
for l in t:
sys.stdout.write(l)
sys.stdout.flush()
time.sleep(random.random()*10.0/typing_speed)
print ''
A: In Python 2.x you can use sys.stdout.write instead of print:
for letter in str:
sys.stdout.write(letter)
time.sleep(.1)
In Python 3.x you can set the optional argument end to the empty string:
print(letter, end='')
A: Try this:
import sys,time
def sprint(str):
for c in str + '\n':
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(3./90)
sprint('hello world') | unknown | |
d15146 | val | I think filtering the Raw data and after that applying, the count would be good option,
;WITH CTE AS (SELECT
(SELECT MAX(LOG_DATE) FROM LOGTABLE WHERE ID=A.ID AND STATUS = 'NEW') AS DATE1,
(SELECT MAX(LOG_DATE) FROM LOGTABLE WHERE ID=A.ID AND STATUS= 'OLD') AS DATE
FROM TABLE1 A
WHERE
A.STATUS ('NEW') OR
A.ID IN (
SELECT DISTINCT ID
FROM LOGTABLE
WHERE LOG_DATE BETWEEN @DATETIME AND @DATETIME AND STATUS = 'OLD'
))
SELECT COUNT(DATE1),COUNT(Date) FROM CTE | unknown | |
d15147 | val | There are a few attributes of a stack-based VM that fit in well with Java's design goals:
*
*A stack-based design makes very few
assumptions about the target
hardware (registers, CPU features),
so it's easy to implement a VM on a
wide variety of hardware.
*Since the operands for instructions
are largely implicit, the object
code will tend to be smaller. This
is important if you're going to be
downloading the code over a slow
network link.
Going with a register-based scheme probably means that Dalvik's code generator doesn't have to work as hard to produce performant code. Running on an extremely register-rich or register-poor architecture would probably handicap Dalvik, but that's not the usual target - ARM is a very middle-of-the-road architecture.
I had also forgotten that the initial version of Dalvik didn't include a JIT at all. If you're going to interpret the instructions directly, then a register-based scheme is probably a winner for interpretation performance.
A: I can't find a reference, but I think Sun decided for the stack-based bytecode approach because it makes it easy to run the JVM on an architecture with few registers (e.g. IA32).
In Dalvik VM Internals from Google I/O 2008, the Dalvik creator Dan Bornstein gives the following arguments for choosing a register-based VM on slide 35 of the presentation slides:
Register Machine
Why?
*
*avoid instruction dispatch
*avoid unnecessary memory access
*consume instruction stream efficiently (higher semantic density per instruction)
and on slide 36:
Register Machine
The stats
*
*30% fewer instructions
*35% fewer code units
*35% more bytes in the instructions stream
*
*but we get to consume two at a time
According to Bornstein this is "a general expectation what you could find when you convert a set of class files to dex files".
The relevant part of the presentation video starts at 25:00.
There is also an insightful paper titled "Virtual Machine Showdown: Stack Versus Registers" by Shi et al. (2005), which explores the differences between stack- and register-based virtual machines.
A: I don't know why Sun decided to make JVM stack based. Erlangs virtual machine, BEAM is register based for performance reasons. And Dalvik also seem to be register based because of performance reasons.
From Pro Android 2:
Dalvik uses registers as primarily units of data storage instead of the stack. Google is hoping to accomplish 30 percent fewer instructions as a result.
And regarding the code size:
The Dalvik VM takes the generated Java class files and combines them into one or more Dalvik Executables (.dex) files. It reuses duplicate information from multiple class files, effectively reducing the space requirement (uncompressed) by half from traditional .jar file. For example, the .dex file of the web browser app in Android is about 200k, whereas the equivalent uncompressed .jar version is about 500k. The .dex file of the alarm clock is about 50k, and roughly twice that size in its .jar version.
And as I remember Computer Architecture: A Quantitative Approach also conclude that a register machine perform better than a stack based machine. | unknown | |
d15148 | val | Why are you casing to a varchar? In SQL Server, you should never use string declarations without a length. But the explicit cast is unnecessary.
Just use:
SELECT Top 1 @filename222 = Name
FROM #MyFiles ;
The default length of varchar -- when used without a length -- depends on the context. You could use an explicit cast(), but you would use varchar(max).
A: What is the name column in your table defined as? Is it also VARCHAR(MAX) or is it defined as VARCHAR(<some number>)
If you already have the value in a table then the variable should be declared as the same data type and then you will never have a truncation issue.
Your issue is likely to be stemming from the fact that the default when no value is added for a VARCHAR declaration will be either 1 or 30 (see https://sqlblog.org/2009/10/09/bad-habits-to-kick-declaring-varchar-without-length) | unknown | |
d15149 | val | <section id="banner">
<?php if( have_rows('slides') ) { ?>
<?php
$num = 0;
$active = 'active';
?>
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<?php while( have_rows('slides') ) : the_row() ; ?>
<li data-target="#carouselExampleIndicators" data-slide-to="<?php echo $num; ?>" class="<?php echo $active; ?>"></li>
<?php
$num++;
$active = '';
?>
<?php endwhile; ?>
</ol>
<div class="carousel-inner">
<?php $active = 'active'; ?>
<?php while( have_rows('slides') ) : the_row() ;
$image = get_sub_field('image');
$mainText = get_sub_field('main_text');
$subText = get_sub_field('sub_text');
?>
<div class="carousel-item <?php echo $active; ?>">
<img class="d-block w-100" src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>">
<div class="carousel-caption d-none d-md-block">
<h5><?php echo $mainText; ?></h5>
<p><?php echo $subText; ?></p>
</div>
</div>
<?php $active = ''; ?>
<?php endwhile; ?>
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
<?php } ?>
</section>
A: If your HTML is like this :
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
</ol>
<div class="carousel-inner" role="listbox">
<div class="carousel-item active">
<img class="d-block img-fluid" src="..." alt="First slide">
</div>
<div class="carousel-item">
<img class="d-block img-fluid" src="..." alt="Second slide">
</div>
<div class="carousel-item">
<img class="d-block img-fluid" src="..." alt="Third slide">
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
Then use this php code :
<?php
$sliders = get_field('slide');
if($sliders){ ?>
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<?php $isActive ='';
foreach($sliders as $key=>$slider){
if($key==0){
$isActive = 'active';
}
echo '<li data-target="#carouselExampleIndicators" data-slide-to="'.$key.'" class="'.$isActive.'"></li>';
} ?>
</ol>
<div class="carousel-inner" role="listbox">
<?php
$activeSlide ='';
foreach($sliders as $key=>$sliderimg){
if($key==0){
$activeSlide = 'active';
}
echo '<div class="carousel-item '.$activeSlide.'">';
echo '<img class="d-block img-fluid" src="'.$sliderimg['image']." alt="First slide">';
echo '</div>';
?>
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
<?php } ?> | unknown | |
d15150 | val | I'll prefer to use CASE here.
UPDATE TAble1
SET Result = CASE value
WHEN 1 THEN x
WHEN 2 THEN y
....
ELSE z
END
or
UPDATE TAble1
SET Result = CASE
WHEN value = 1 THEN x
WHEN value = 2 THEN y
....
ELSE z
END | unknown | |
d15151 | val | There's an [int Row, int Col] indexer on Cells (type ExcelRange), so you can use ws.Cells[i, 0].
int i = 1;
foreach (var item in items)
{
ws.Cells[i, 0].Value =item.Text;
i++;
} | unknown | |
d15152 | val | The problem is with these lines:
Input('my-date-picker-range2', 'start_date2'),
Input('my-date-picker-range2', 'end_date2')
start_date2 and end_date2 are not valid properties of dcc.DatePickerRange, so change these instances to start_date and end_date. | unknown | |
d15153 | val | Here is one approach using glob module to match the pathnames of the modules we would like to import and importlib's SourceFileLoader to import.
from glob import glob
from importlib.machinery import SourceFileLoader
modules = glob('foo/*.py')
bars = list(map(lambda pathname: SourceFileLoader(".", pathname).load_module().Bar, modules))
A: You can use importlib to import the modules dynamically. But you need to find them first. If you include foo.__init__.py in the source, then then foo.__file__ will be that name. You can use that as the base of your glob, but you need to make sure you don't try to import __init__.py itself. This technique is nice because you don't have to worry about another bit of source importing the same module name but getting a different module in memory.
from pathlib import Path
import importlib
import foo
def no_magic(paths):
for path in paths:
if not path.name.startswith("_"):
yield path
bars = []
for py in no_magic(Path(foo.__file__).resolve().parent.glob("*.py")):
mod = importlib.import_module(f"foo.{py.stem}", foo)
bars.append(mod.Bar)
print(bars) | unknown | |
d15154 | val | There are a couple of ways to handle this. You can either create a source method so that if the results from the filter are empty, you add "no results" as a value, or you handle the response event to display a message that no results where returned in your ui. If using the source method, then add a select handler to prevent No Result from being a value.
var availableTags = ['Abc', 'Def', 'ghi'];
$('#noresults').autocomplete({
source: function (request, response) {
var responses = $.ui.autocomplete.filter(availableTags, request.term);
if (responses.length == 0) responses.push('No Result');
response(responses);
},
response: function (event, ui)
{
if (ui.content.length == 0) {
console.log('No results');
}
},
select: function (event, ui) {
// don't let no result get selected
return (ui.item.value != 'No Result');
}
}); | unknown | |
d15155 | val | My answer is a little more involved than yours, but hopefully it will point you in the right direction.
When you want to change a remote source using bloodhound, you will have to clear the bloodhound object and reinitialize it.
Here I am creating an initializing a bloodhound instance:
var taSource = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('Value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
identify: function(obj) {
return obj.Value;
},
remote: remoteSrc
});
taSource.initialize(true);
In the logic to switch I call both clear() and initialize(true), passing true for the reinitialize paramter:
taSource.clear();
taSource.initialize(true);
I handle changing the URL in the prepare method that is available as part of the remote object.
prepare: function(query, settings) {
settings.url = urlRoot + '/' + whichType + '?q=' + query;
console.log(settings.url);
return settings;
},
Here is a full example show how I handle it. | unknown | |
d15156 | val | Run the image using --rm parameter (which removes the container upon exit).
docker run --rm -p 3000:3000 docker.pkg.github.com/UserName/Project/newImageName:1
After exiting (stopping the container) you can docker pull to get the latest version of the image and then re-run | unknown | |
d15157 | val | Regarding the first part of your question, as dan stated in the comments you should be using fullPath.appendingPathComponent(name) instead.
Regarding your second question:
The main difference between writeToFile and write(to: is the fact that the first is for Strings and the seconds is for NSData.
Somewhat related:
According to the NSData Class Reference
In iOS 2.0+ you have:
write(to:atomically:)
and
write(toFile:atomically:)
Given:
Since at present only file:// URLs are supported, there is no
difference between this method and writeToFile:atomically:, except for
the type of the first argument.
None of this has changed in Swift 3 according to the Swift Changelog. | unknown | |
d15158 | val | Allright, first take a deep breath. You are probably not going to like some of my answers but you'll be living with the same issues that we all are.
*
*The best thing to do in this case is to use something like the KeyChain plugin to retrieve your security keys from the native side.
*You can take PhoneGap out of the question because it applies to any situation where you send unencrypted data between a client and server. Anyone can easily listen in using a number of tools including Wireshark or Ethereal. If you need to communicate with a sever it should be done on an encrypted, HTTPS or SSL, connection.
*First I think you are under the mistaken impression that PhoneGap compiles your HTML/JS code into Obj-C. It does not. If the user uncompresses your app they will be able to read your HTML/JS. Also, they'll be able to decompile your Obj-C code as well. This does not take a powerful PC or even an experienced hacker. Pretty much anyone can do it.
My advice to you is not to worry about it. Put your time into creating a truly great app. The people who will pay for it will pay for it. The folks who decompile it would never buy the app no matter what. The more time you take trying to combat the hackers takes away from the time you could use to make your app greater. Also, most anti-hacking measures just make life harder for your actual users so in fact they are counter productive.
A: TLDR -
Consider that you are coding a website and all code ( html and js ) will be visible to user with
Crtl+Shift+i as in browsers
Some points for ensuring maximum security
*
*If your using backend then recheck everything coming from the app
*All attacks possible on websites (XSS, redicting to malacious webistes , cloning webistes, etc are possible )
*All the data sent to the app will finally be available in some js variables / resource files , Since all variables are accessible by hacker so is all the data sent to app EVEN IF YOU ARE USING THE MOST SECURE DATA TRANSMISSION MECHANISMS
*As Simon correctly said in his ans , phonegap or cordova does not convert html / js to native code . Html / Js is available as-it-is
Cordova also explicitly mentions this in their official statement
Do not assume that your source code is secure
Since a Cordova application is built from HTML and JavaScript assets that get packaged in a native container, you should not consider your code to be secure. It is possible to reverse engineer a Cordova application.
5.Mainly all the techniques which are used by websites to prevent their code from being cloned / easily understood are applicable even here (Mainly it includes converting js code into hard to read format - obfuscating code)
6.Comparing native apps with cordova/phonegap apps native apps , I would say that cordova are easier for hacker only because of lack of awareness between cordova developers who do not take enough measures to secure it and lack of readily available(one click ) mechanisms to directly obfuscate the code vs in android proguard
Sample Cordova App Hacking (NOTE:Phonegap also works in similar way)
I'll show an example to show how easy is it for hacker to hack a cordova app(where developer has taken no efforts in obfuscating the code )
basically we start with unzipping the apk files (apks can be unzipped like zip files )
The contents inside will be similar to this
The source code for cordova apps is present in /assets/www/ folder
As you can see all the contents including any databases that you have packed with the app are visible(see last 2 rows have a db file )
Along with it any other resources are also directly visible (text files/js / html/ audio / video / etc)
All the views / controllers are visible and editable too
Further exploring the contents we find a PaymentController.js file
Opening it we can directly see the js code and other comments
here we note that after user performs payment if it is successful then successCallback is called else cancelCallback is called.
Hacker can simply replace the two functions so that when payment is not successful successCallback is called .
In absence of other checks the hacker has successfully bypassed payment. | unknown | |
d15159 | val | See Rotation Matrix for the mathematical background/formula, section "Rotation matrix from axis and angle".
If you'd like to use a library: Math.NET Iridium (and its successor Math.NET Numerics) are numerical methods libraries, but you could use Math.NET Spatial instead.
var point = new Point3D(1,1,1);
var vector = new Vector3D(0,0,1);
// will have coordinates (-1,-1,1)
var rotated = point.Rotate(vector, Angle.FromDegrees(180));
Note that Math.NET Spatial is in a very early phase, so there is no release or NuGet package yet. But you can compile it yourself, or simply have a look at the code to see how it was implemented. | unknown | |
d15160 | val | The other approach is to do a weighted least squares solution. You need the (x,y) location of each pixel and the number of counts n within each pixel. Then, I think that you'd do the weighted least-squares this way:
%gather your known data...have x,y, and n all in the same order as each other
A = [x(:) ones(length(x),1)]; %here are the x values from your histogram
b = y(:); %here are the y-values from your histogram
C = diag(n(:)); %counts from each pixel in your 2D histogram
%Define polynomial coefficients as p = [slope; y_offset];
%usual least-squares solution...written here for reference
% b = A*p; %remember, p = [slope; y_offset];
% p = inv(A'*A)*(A'*b); %remember, p = [slope; y_offset];
%We want to apply a weighting matrix, so incorporate the weighting matrix
% A' * b = A' * C * A * p;
p = inv(A' * C * A)*(A' * b); %remember, p = [slope; y_offset];
The biggest uncertainty for me with this solution is whether the C matrix should be made up of n or n.^2, I can never remember. Hopefully, someone can correct me in the comments, if needed.
A: If you have the original data, which is a collection of (x,y) points, you simply do a polyfit on the original data:
p = polyfit(x(:),y(:),1); %linear fit
That will give you a best fit (in the least-squares sense) to the original data, which is what you want.
If you do not have the original data, and you only have the 2D histogram, the approach that you defined (which basically recreates a facsimile of the original data) will give a similar answer as if you did the polyfit on the original data. | unknown | |
d15161 | val | You shouldn't pass optional parameters before required ones. Try this:
public function reservationToGuest(Request $request, $idreservation = null)
{
// ...
} | unknown | |
d15162 | val | You need to find the GameObject that contains the script Component that you plan to get a reference to. Make sure the GameObject is already in the scene, or Find will return null.
GameObject g = GameObject.Find("GameObject Name");
Then you can grab the script:
BombDrop bScript = g.GetComponent<BombDrop>();
Then you can access the variables and functions of the Script.
bScript.foo();
I just realized that I answered a very similar question the other day, check here:
Don't know how to get enemy's health
I'll expand a bit on your question since I already answered it.
What your code is doing is saying "Look within my GameObject for a BombDropScript, most of the time the script won't be attached to the same GameObject.
Also use a setter and getter for maxBombs.
public class BombDrop : MonoBehaviour
{
public void setMaxBombs(int amount)
{
maxBombs += amount;
}
public int getMaxBombs()
{
return maxBombs;
}
}
A: use it in start instead of awake and dont use Destroy(gameObject); you are destroying your game Object then you want something from it
void Start () {
BombDropScript =gameObject.GetComponent<BombDrop> ();
collider = gameObject.GetComponent<BoxCollider2D> ();
// Call the Explode function after a few seconds
Invoke("Explode", time);
}
void Explode() {
//..
//..
//at last
Destroy(gameObject);
}
if you want to access a script in another gameObject you should assign the game object via inspector and access it like that
public gameObject another;
void Start () {
BombDropScript =another.GetComponent<BombDrop> ();
}
A: Can Use this :
entBombDropScript.maxBombs += 1;
Before :
Destroy(gameObject);
I just want to say that you can increase the maxBombs value before Destroying the game object. it is necessary because, if you destroy game object first and then increases the value so at that time the reference of your script BombDropScript will be gone and you can not modify the value's in it. | unknown | |
d15163 | val | There is a note on bound services... The part under additional notes should be useful. I think trapping the exception is probably what you should do...
try {
// Do stuff
} catch(DeadObjectException e){
// Dead object
}
I read that object lifetimes should be reference counted by android across processes, so you should be OK, when the client dies I wonder if
_outputMessenger // needs to be unassigned in your service...?
I assume what is happening is that your binding to the service, it's pumping some data back to your client, your client goes away, the service continues running but then needs to pump some data to the client which has gone by this point?
Also this link | unknown | |
d15164 | val | id, time (pk: id)
Table B: id(fk), key, value (pk: id, key)
Where the id of Table B is a foreign key to Table A and the primary keys are as specified.
I need the latest (in time) value of the requested keys. So, say I have data like:
id | key | value
1 | A | v1
1 | B | v2
1 | C | v3
2 | A | v4
2 | C | v5
3 | B | v6
3 | D | v7
Where time is increasing for the id, and I want values for keys A and C, I would expect a result like:
key | value
A | v4
C | v5
Or for keys D and A:
key | value
D | v7
A | v4
Ideally, I'd only get n rows back for n key requests. Is something like this possible with a single query?
A: Here is it working with SQL Server 2008 R2:
Schema
CREATE TABLE B (
ind integer,
[key] varchar(8),
value varchar(16)
);
INSERT INTO B VALUES (1, 'A', 'v1');
INSERT INTO B VALUES (1, 'B', 'v2');
INSERT INTO B VALUES (1, 'C', 'v3');
INSERT INTO B VALUES (2, 'A', 'v4');
INSERT INTO B VALUES (2, 'C', 'v5');
INSERT INTO B VALUES (3, 'B', 'v6');
INSERT INTO B VALUES (3, 'D', 'v7');
INSERT INTO B VALUES (3, 'A', 'v12');
INSERT INTO B VALUES (3, 'C', 'v17');
INSERT INTO B VALUES (3, 'C', 'v101');
Query
select [key], max(CAST(SUBSTRING(value, 2, LEN(value)) as INT)) from B
where [key] in ('A', 'C')
group by [key]
If you want to keep the v as a prefix, do this:
select [key], 'v' + CAST(max(CAST(SUBSTRING(value, 2, LEN(value)) as INT)) as VARCHAR) as Value
from B
where [key] in ('A', 'C')
group by [key]
Output
| KEY | VALUE |
------------------
| A | v12 |
| C | v101 |
The SQL Fiddle to play with: http://sqlfiddle.com/#!3/9de72/1
A: I'm assuming that no ID values will have the same TIME value.
I believe the following is about as generic as you can get with the option of running on as many databases as possible. But the trade off for platform flexibility is less than optimal performance.
The sub-query with alias t identifies the latest time available for each key.
select a.id,
a.time,
b.key,
b.value
from tableB as b
inner join tableA as a
on a.id=b.id
inner join (
select b2.key,
max(a2.time) time
from tableB as b2
inner join tableA as a2 on a2.id=b2.id
group by b2.key
) as t on a.time = t.time and b.key = t.key
where b.key in ('D','A')
The WHERE clause could be moved inside the sub-query and it might perform slightly better on a database that has a primitive optimizer. But putting the WHERE clause in the outer query makes it easier to maintain, and also leaves open the possibility of creating a view without the WHERE clause. The WHERE clause can then be added to a select from the view.
A query using ROW_NUMBER() would be more efficient, or even better yet a query using something like Oracle's KEEP LAST. But those features would make the query more restrictive to certain platforms. | unknown | |
d15165 | val | If I get this right, I might have something useful. Referring to your sample at https://gist.github.com/d11wtq/9575063, you cannot have
class ASTNode {
public:
template <class T>
virtual T accept(Visitor<T> *visitor);
};
because there are no template virtual functions. However, you may have a generic class
template <class D, class T>
struct host {
virtual T accept(Visitor<T> * visitor);
// I guess, { return visitor->visit(static_cast <D*>(this)); }
};
and a collection
template <class D, class... T>
struct hosts : host <D, T>... { };
so that, when the set of possible return types is limited, you can say e.g.
class ASTNode : public hosts <ASTNode, T1, T2, T3> {
public:
// ...
};
Now you have three different Visitor contracts of return types T1,T2,T3.
A: Maybe this is helpful.
Using return type covariance to make accept() calls type-safe:
class Visitor;
class ASTNode
{
public:
virtual ASTNode* accept(Visitor* visitor);
};
class CallNode;
class BinaryExpressionNode;
class Visitor
{
public:
virtual CallNode* visit(CallNode* node) = 0;
virtual BinaryExpressionNode* visit(BinaryExpressionNode* node) = 0;
};
Implementations:
class CallNode : public ASTNode
{
public:
CallNode(BinaryExpressionNode* left, BinaryExpressionNode* right);
// return type covariance
CallNode* accept(Visitor* visitor) override
{
return visitor->visit(this);
}
BinaryExpressionNode* left();
BinaryExpressionNode* right();
};
class BinaryExpressionNode : public ASTNode
{
public:
BinaryExpressionNode* accept(Visitor* visitor) override
{
return visitor->visit(this);
}
}
class OptimizingVisitor : public Visitor
{
public:
CallNode* visit(CallNode* node) override
{
// return type covariance will make this operation type-safe:
BinaryExpressionNode* left = node->left()->accept(this);
auto right = node->right()->accept(this);
return new CallNode(left, right);
}
BinaryExpressionNode* visit(BinaryExpressionNode* node) override
{
return new BinaryExpressionNode(node);
}
}; | unknown | |
d15166 | val | Dictionary is an unordered collection of data, so you can't create an ordered dictionary.
A: Try This:
for i in 0..<parameters!.count {
let key = "q\(i)"
if httpBody.contains(key){
let regex = try! NSRegularExpression(pattern: "\\b\(key)\\b", options: .caseInsensitive)
httpBody = regex.stringByReplacingMatches(in: httpBody, options: [], range: NSRange(0..<httpBody.utf16.count), withTemplate: "q")
}
}
Simple sort function will not work here. | unknown | |
d15167 | val | The .bak file should have everything of the database it was made from - tables, sprocs and data.
To restore it, right-click the Databases folder in the Object Explorer and choose Restore Database.
Type in a name you wish to use for the restored database in the To database: field.
Then select the From device: radio button and press the ... button to select your .bak file: in the window that appears press the Add button and select the correct file, then press OK. | unknown | |
d15168 | val | Remove this line from Button Layout properties.
android:layout_below="@id/generated_number_gridview"
This means that It should be below the GridView. And your GridView size is not fixed. Since the renderer shows the GridView with multiple elements it fills the screen and your Button goes below that. That's why it's not visible.
I hope this is the UI that you are looking for.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<GridView
android:id="@+id/generated_number_gridview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnWidth="90sp"
android:horizontalSpacing="10sp"
android:stretchMode="columnWidth"
android:verticalSpacing="10sp"
android:layout_above="@+id/proceedButton"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:id="@+id/proceedButton"
android:onClick="proceed"
android:text="proceed"
android:textSize="25sp" />
</RelativeLayout>
Hope it helps.
A: Try this.
Just replace this with your XML code.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<GridView
android:id="@+id/generated_number_gridview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/btnProceed"
android:layout_centerHorizontal="true"
android:columnWidth="90sp"
android:horizontalSpacing="10sp"
android:stretchMode="columnWidth"
android:verticalSpacing="10sp" />
<Button
android:id="@+id/btnProceed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="proceed"
android:text="Proceed"
android:textSize="25sp" />
</RelativeLayout>
Here is the Screen shot.
A: You can use this layout..
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<GridView
android:id="@+id/generated_number_gridview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
**android:layout_above="@+id/btn_proceed"**
android:layout_centerHorizontal="true"
android:columnWidth="90sp"
**android:horizontalSpacing="10dp**"
android:stretchMode="columnWidth"
**android:verticalSpacing="10dp"** />
<Button
android:id="@+id/btn_proceed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="proceed"
android:text="@string/proceed"
android:textSize="25sp" />
</RelativeLayout> | unknown | |
d15169 | val | The pthread_cond_wait() in the main thread unlocks the mutex and waits for the condition to be signalled — and relocks the mutex before returning.
The child thread is able to lock the mutex, manipulate the buffer, signal the condition and then unlock the mutex, letting the main thread reacquire the lock.
Consequently, the code is well-behaved — give or take the need to worry about 'spurious wakeups' in more general situations with multiple child threads. I don't think you can get a spurious wakeup here.
A: What this code is doing is valid.
When the thread calls pthread_cond_signal it doesn't immediately cause the main thread to grab the mutex, but wakes up the main thread so it can attempt to lock it. Then once the thread releases the mutex, the main thread is able to lock it and return from pthread_cond_wait. | unknown | |
d15170 | val | In this case using combine_first
df1.set_index('id').combine_first(df2.set_index('id')).reset_index()
Out[766]:
id metric1 metric2
0 a 123.0 1.0
1 b 22.0 2.0
2 c 356.0 3.0
3 d 412.0 4.0
4 f 54.0 5.0
5 g 634.0 6.0
6 h 72.0 7.0
7 j 812.0 8.0
8 k 129.0 9.0
9 l 110.0 10.0
10 m 200.0 11.0
11 q 812.0 NaN
12 w 110.0 NaN
13 z 129.0 NaN | unknown | |
d15171 | val | Use Django's lovely aggregation features.
queryset = Category.objects.annotate(expense_count=Count('expense')).order_by('-expense_count')
A: We can use annotate to achieve this:
from django.db.models import Count
...
queryset = Category.objects.annotate(expense_count=Count('expense')).order_by('-expense_count')
A: from django.db.models import Count
Category.objects.annotate(expense_count=Count('category')).order_by('-expense_count')
This is based on your model definition yet I suggest that the related_name should be modified to a term that related to Expense, such as expenses. Since the related_name indicate the name you are using for reverse querying.
A: Just add .distinct('field-name') at end of the query. like this
queryset = Category.objects.order_by("-expense__expense").distinct('category') | unknown | |
d15172 | val | You need to use ajax to send sometime from java to a php file. below is a tutorial on how to use ajax.
http://www.w3schools.com/ajax/
A: If you need to pass the input value to another php, you must to use Ajax in jQuery, I hope this example will help you
$.ajax({
type:"get",
url:"sending_msg_to_user.php",
data:"InputMessage="+InputMessage,
beforeSend: function(){
$('#some_div').html('<img src="img/Loading.gif"/> Sending Data');
},
success:function(data){
alert(data);
$('#some_div').html('');
}
});
If you have an echo in sending_msg_to_user.php you could see in an alert message tha value of inpu in prompt
A: Your $.getJSON request is poorly formed. If you paste that function directly into your favorite JavaScript console and hit 'enter', you would see the error:
Uncaught SyntaxError: Unexpected token }
at Object.InjectedScript._evaluateOn (<anonymous>:905:140)
at Object.InjectedScript._evaluateAndWrap (<anonymous>:838:34)
at Object.InjectedScript.evaluate (<anonymous>:694:21)
Try something like:
$.getJSON('sending_msg_to_user.php?userinput=' + InputMessage); | unknown | |
d15173 | val | Instead of using 2 different methods for search, try combining both in index method. Your index method will now look as follows:
def index
if params[:search]
@availabilities = Availability.unmatched.search(search_params[:start_city])
else
@availabilities = Availability.unmatched
end
end
Change the form url to search_rides_path. This way search results will be rendered in same view upon form submission. | unknown | |
d15174 | val | It's difficult to answer without a minimal working example. I'm going to give it a shot. Based on what you wrote the inference is you have the following. Forget for a moment that it's red-black, that detail doesn't really matter for this problem. With just a regular BST you have:
class Test<T extends Comparable<T>> {
class Node<T> {
T data;
Node<T> left;
Node<T> right;
Node(T data) {
this.data = data;
}
}
Node<T> search(Node<T> root, T data) {
if (root == null || root.data == data || root.data.equals(data)) {
return root;
}
if (root.data.compareTo(data) < 0) {
return search(root.right, data);
}
return search(root.left, data);
}
// etc ...
}
Looking at just the search method, you need to compare the whole data object.
Now throw a StudentData class into the mix. It has to implement Comparable otherwise you have no way of comparing it to another StudentData with a generic as just defined.
class StudentData implements Comparable<StudentData> {
final String name;
final double grade;
StudentData(String name, double grade) {
this.name = name;
this.grade = grade;
}
@Override
public int compareTo(StudentData o) {
return Double.compare(this.grade, o.grade);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StudentData that = (StudentData) o;
return Double.compare(that.grade, grade) == 0 && Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(name, grade);
}
}
Note that here we can compare based on the grade because it's defined right within the student data class. | unknown | |
d15175 | val | You can use the following classes as example:
[Serializable]
public abstract class BaseMessage
{
public byte[] ToBinary()
{
BinaryFormatter bf = new BinaryFormatter();
byte[] output = null;
using (MemoryStream ms = new MemoryStream())
{
ms.Position = 0;
bf.Serialize(ms, this);
output = ms.GetBuffer();
}
return output;
}
public static T FromMessage<T>(CloudQueueMessage m)
{
byte[] buffer = m.AsBytes;
T returnValue = default(T);
using (MemoryStream ms = new MemoryStream(buffer))
{
ms.Position = 0;
BinaryFormatter bf = new BinaryFormatter();
returnValue = (T)bf.Deserialize(ms);
}
return returnValue;
}
}
Then a StdQueue (a Queue that is strongly typed):
public class StdQueue<T> where T : BaseMessage, new()
{
protected CloudQueue queue;
public StdQueue(CloudQueue queue)
{
this.queue = queue;
}
public void AddMessage(T message)
{
CloudQueueMessage msg =
new CloudQueueMessage(message.ToBinary());
queue.AddMessage(msg);
}
public void DeleteMessage(CloudQueueMessage msg)
{
queue.DeleteMessage(msg);
}
public CloudQueueMessage GetMessage()
{
return queue.GetMessage(TimeSpan.FromSeconds(120));
}
}
Then, all you have to do is to inherit the BaseMessage:
[Serializable]
public class ParseTaskMessage : BaseMessage
{
public Guid TaskId { get; set; }
public string BlobReferenceString { get; set; }
public DateTime TimeRequested { get; set; }
}
And make a queue that works with that message:
CloudStorageAccount acc;
if (!CloudStorageAccount.TryParse(connectionString, out acc))
{
throw new ArgumentOutOfRangeException("connectionString", "Invalid connection string was introduced!");
}
CloudQueueClient clnt = acc.CreateCloudQueueClient();
CloudQueue queue = clnt.GetQueueReference(processQueue);
queue.CreateIfNotExist();
this._queue = new StdQueue<ParseTaskMessage>(queue);
Hope this helps!
A: Extension method that uses Newtonsoft.Json and async
public static async Task AddMessageAsJsonAsync<T>(this CloudQueue cloudQueue, T objectToAdd)
{
var messageAsJson = JsonConvert.SerializeObject(objectToAdd);
var cloudQueueMessage = new CloudQueueMessage(messageAsJson);
await cloudQueue.AddMessageAsync(cloudQueueMessage);
}
A: I like this generalization approach but I don't like having to put Serialize attribute on all the classes I might want to put in a message and derived them from a base (I might already have a base class too) so I used...
using System;
using System.Text;
using Microsoft.WindowsAzure.Storage.Queue;
using Newtonsoft.Json;
namespace Example.Queue
{
public static class CloudQueueMessageExtensions
{
public static CloudQueueMessage Serialize(Object o)
{
var stringBuilder = new StringBuilder();
stringBuilder.Append(o.GetType().FullName);
stringBuilder.Append(':');
stringBuilder.Append(JsonConvert.SerializeObject(o));
return new CloudQueueMessage(stringBuilder.ToString());
}
public static T Deserialize<T>(this CloudQueueMessage m)
{
int indexOf = m.AsString.IndexOf(':');
if (indexOf <= 0)
throw new Exception(string.Format("Cannot deserialize into object of type {0}",
typeof (T).FullName));
string typeName = m.AsString.Substring(0, indexOf);
string json = m.AsString.Substring(indexOf + 1);
if (typeName != typeof (T).FullName)
{
throw new Exception(string.Format("Cannot deserialize object of type {0} into one of type {1}",
typeName,
typeof (T).FullName));
}
return JsonConvert.DeserializeObject<T>(json);
}
}
}
e.g.
var myobject = new MyObject();
_queue.AddMessage( CloudQueueMessageExtensions.Serialize(myobject));
var myobject = _queue.GetMessage().Deserialize<MyObject>();
A: In case the storage queue is used with WebJob or Azure function (quite common scenario) then the current Azure SDK allows to use POCO object directly. See examples here:
*
*https://learn.microsoft.com/en-us/sandbox/functions-recipes/queue-storage
*https://github.com/Azure/azure-webjobs-sdk/wiki/Queues#trigger
Note: The SDK will automatically use Newtonsoft.Json for serialization/deserialization under the hood.
A: I liked @Akodo_Shado's approach to serialize with Newtonsoft.Json. I updated it for Azure.Storage.Queues and also added a "Retrieve and Delete" method that deserializes the object from the queue.
public static class CloudQueueExtensions
{
public static async Task AddMessageAsJsonAsync<T>(this QueueClient queueClient, T objectToAdd) where T : class
{
string messageAsJson = JsonConvert.SerializeObject(objectToAdd);
BinaryData cloudQueueMessage = new BinaryData(messageAsJson);
await queueClient.SendMessageAsync(cloudQueueMessage);
}
public static async Task<T> RetreiveAndDeleteMessageAsObjectAsync<T>(this QueueClient queueClient) where T : class
{
QueueMessage[] retrievedMessage = await queueClient.ReceiveMessagesAsync(1);
if (retrievedMessage.Length == 0) return null;
string theMessage = retrievedMessage[0].MessageText;
T instanceOfT = JsonConvert.DeserializeObject<T>(theMessage);
await queueClient.DeleteMessageAsync(retrievedMessage[0].MessageId, retrievedMessage[0].PopReceipt);
return instanceOfT;
}
}
The RetreiveAndDeleteMessageAsObjectAsync is designed to process 1 message at time, but you could obviously rewrite to deserialize the full array of messages and return a ICollection<T> or similar.
A: That is not right way to do it. queues are not ment for storing object. you need to put object in blob or table (serialized).
I believe queue messgae body has 64kb size limit with sdk1.5 and 8kb wih lower versions.
Messgae body is ment to transfer crutial data for workera that pick it up only. | unknown | |
d15176 | val | While Helm hooks are typically Jobs, there's no requirement that they are, and Helm doesn't do any analysis on the contents of a hook object to see what else it might depend on. If you read through the installation sequence described there, it is (7) install things tagged as hooks, (8) wait for those to be ready, then (9) install everything else; it waits for the Job to finish before it installs the Secret it depends on.
The first answer, then, is that you also need to tag your Secret as a hook for it to be installed during the pre-install phase, with a modified weight so that it gets installed before the main Job (smaller weight numbers happen sooner):
apiVersion: v1
kind: Secret
annotations:
"helm.sh/hook": pre-install
"helm.sh/hook-weight": "-5"
The next question is when this Secret gets deleted. The documentation notes that helm uninstall won't delete hook resources; you need to add a separate helm.sh/hook-delete-policy annotation, or else it will stick around until the next time the hook is scheduled to be run. This reads to me as saying that if you modify the Secret (or the values that make it up) and upgrade (not delete and reinstall) the chart, the Secret won't get updated.
I'd probably just create two copies of the Secret, one that's useful at pre-install time and one that's useful for the primary chart lifecycle. You could create a template to render the Secret body and then call that twice:
{{- define "secret.content" -}}
type: Opaque
data:
PROP_FROM_SCRETS: eHB0bw==
{{- end -}}
---
apiVersion: v1
kind: Secret
metadata:
name: "SecretsFileName"
labels:
app: "MyAppName"
{{ include "secret.content" . }}
---
apiVersion: v1
kind: Secret
metadata:
name: "SecretsFileName-preinst"
labels:
app: "MyAppName"
annotations:
"helm.sh/hook": pre-install
"helm.sh/hook-weight": "-5"
"helm.sh/hook-delete-policy": hook-succeeded
{{ include "secret.content" . }}
A: According to the docs:
pre-install: Executes after templates are rendered, but before any resources are created in Kubernetes | unknown | |
d15177 | val | it is because the default column is typename + id for the reference which happens to be the same name as the id column. Explicitly state it in the reference.
References(n => n.Parent, "ParentId").LazyLoad().Nullable();
Update: as convention
public class ReferenceColumnConvention : IReferenceConvention
{
public void Apply(IManyToOneInstance instance)
{
// uncomment if needed
//if (instance.EntityType == instance.Property.PropertyType)
instance.Column(instance.Name + "id");
}
} | unknown | |
d15178 | val | I had the same problem but solved it by deleting configuration files from previous Android Studio installations as described here
(Section: Studio doesn't start after upgrade).
A: I did a fresh install of Big Sur yesterday on my Catalina machine. Today I updated my Android Studio 3.5.3 installation there to latest Android 4.1.1 and had no issues with running and building with Android Studio 4.1.1 for my Android native and React Native apps. | unknown | |
d15179 | val | Maybe there's an easier way to do this. However, I think a custom rule as such should work.
$validator = Validator::make($request->all(), [
'image' => [
'required',
function ($attribute, $value, $fail) {
if(is_file($value)) {
if (true !== mb_strpos($value->getMimeType(), "image")) {
return $fail($attribute.' is invalid.');
}
}
if (is_string($value)) {
if(! file_exists($value)) {
return $fail($attribute.' is invalid.');
}
}
},
],
]);
A: i found my answer with FormRequest
MyTestFormRequest
<?php
use Illuminate\Foundation\Http\FormRequest;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class MyTestFormRequest extends FormRequest
{
public function rules()
{
$rules = [
"image" => ['required']
];
if(is_string($this->image)) {
$rules['image'][] = new FileExistsRule;
} else if($this->image instanceof UploadedFile) {
$rules['image'][] = 'image';
$rules['image'][] = 'dimensions:ratio=1/1';
}
return $rules;
}
}
FileExistsRule
<?php
use Illuminate\Contracts\Validation\Rule;
class FileExistsRule implements Rule
{
public function passes($attribute, $value)
{
return file_exists(public_path($value));
}
public function message()
{
return 'The file not exists';
}
} | unknown | |
d15180 | val | I solved this by creating a messagedialog that showed me the output of mynotebook.CurrentPage. It turned out that each page was assigned a number starting with 0.
This is the working code:
protected void OnRefreshActionActivated (object sender, EventArgs e)
{
if (nbMain.CurrentPage == 0)
{
lblMsg.Text = "You are viewing the first page.";
}
else
{
lblMsg.Text = "You are viewing the first page.";
}
} | unknown | |
d15181 | val | It seems to be a core bug. I might be able to answer to why this issue occurs.
I am guessing that this issue is caused by int(-1).
When writing data, RedisEngine doesn't serialize the data if it is an integer.
Therefore, int(-1) will be saved without calling serialize().
public function write($key, $value, $duration) {
if (!is_int($value)) {
$value = serialize($value);
}
...
}
But when reading data, the implementation seems asymmetric. I don't know Redis well, but I am guessing that Redis stores int(-1) as string(-1). As ctype_digit("-1") returns false, string(-1) would be unserialized wrongly.
public function read($key) {
$value = $this->_Redis->get($key);
if (ctype_digit($value)) { // ctype_digit("-1") === false
$value = (int)$value;
}
if ($value !== false && is_string($value)) { // is_string("-1") === true
$value = unserialize($value);
}
...
}
Thus, you will see "Notice (8): unserialize(): Error at offset 0 of 2 bytes". The size of string(-1) is 2 bytes.
What about opening an issue on github, if you could reproduce that writing int(-1) and reading it throws a notice.
Aside from that, a workaround would be stop using Cache::decrement(). On race conditions, the method will store int(-1).
You may use Cache::write() instead if it is not an important data. For example:
$count = Cache::read('item' . $id. '_count', 'my_counts');
if ($count === false || 0 > $count - $offset) {
$this->getCount($id);
} else {
Cache::write('item' . $id. '_count', $count - $offset, 'my_counts');
}
But if it is an important data, then you may need to implement exclusive lock/unlock.
Thank you for reading this to the end and sorry if I am wrong.
A: Solution:
return ($count === false) ? 0 : (int)$count;
Long version:
You shouldn't increment/decrement serialized value.
Cache::remember does something like this:
$key = 'key';
$value = 10;
$serialized = serialize($value); // $serialized = 'i:10;'
$redis->set($key, $serialized);
Cache::read does something like this:
$key = 'key';
$serialized = $redis->get($key); // $serialized = 'i:10;'
$value = unserialize($serialized); // $value = (int) 10
return $value;
But Cache::decrement does something like this:
$key = 'key';
$count = 1;
$redis->decrby($key, $count); // Error, decrby expects plain value, "10", not "i:10;" ( http://redis.io/commands/decrby )
Also, if you decrement successfully, then you will have plain value in redis, so result will be:
$key = 'key';
$serialized = $redis->get($key); // $serialized = '10'
$value = unserialize($serialized); // error, cannot unserialize '10'
EDIT:
After checking source:
https://github.com/cakephp/cakephp/blob/master/src/Cache/Engine/RedisEngine.php
I see that Cake does checks:
if (!is_int($value)) {
$value = serialize($value);
}
So all you need to do to avoid serialization is to make sure that you are storing (int).
A: Just remove third parameter, it should be work
return Cache::remember('item' . $id. '_count', function() use ($model, $id) {
$count = $model->find('count', array(
'conditions' => array(
$model->alias . '.status' => 1,
$model->alias . '.id' => $id
)
));
return ($count === false) ? 0 : (int)$count;
}); | unknown | |
d15182 | val | You're using the Notes "front-end" classes rooted at Notes.NotesUIWorkspace. These are OLE classes, which means that they need the Notes client to be running and they work on the open document. There are also back-end classes rooted at Notes.NotesSession. These are also OLE classes, so they still need the Notes client to be running but they can access other documents (and other databases, servers, etc.). There is also a set of back-end classes rooted at Lotus.NotesSession. Note the different prefix. These are COM classes, so they do not need the Notes client to be running - though it does have to be installed and configured, and your code will have to provide the user's password since the client won't prompt for it.
You can find documentation and examples for the NotesSession class here. Down near the bottom of the page, you'll find links to information about using them via OLE or COM. You can find a bunch of examples based on using the COM classes here, including one that traverses the documents in a view in database. Apart from the inital setup of the session, it would be the same if you use OLE.
A: It is possible, and also better to use the 'Back end' object Notes.NotesSession. So try this:
Set doc = view.GetFirstDocument
While Not (doc Is Nothing)
'Check if you have the field in the document
if doc.HasItem("RevDueDate") Then
revDate = doc.getFirstItem("RevDueDate").Text
End If
Set doc = view.GetNextDocument(doc)
Wend
It is also possible to use Notes.NotesUiWorkspaceobject by opening every document in the client, getting the fields data and closing the document but I would highly recommend NOT TO make it like this as there is high possibility that you will crash the Notes client, if you need to loop on more documents. | unknown | |
d15183 | val | The browser that gets used is a user setting on the device based on what they have installed, not something you can control. Best you can do is recommend that it works best in Safarior or whichever browser.
A: Excerpt from Quora:
The short answer you can't specify that a specific browser will be opened by a hyperlink.
If you are viewing a web page or an app or something that shows a hyperlink and you click on that link then the operating system will receive an event that indicates a hyperlink was launched. It will then look for the default browser, launch that browser and then pass the URL to the browser.
You can change the default browser at any time but the operating system will only open that specify browser.
If you were really determined you might be able to write multiple browser launcher browsers that you would register with the operating system. Then any time you clicked on a link your browser would launch and you could present yourself with a list of alternative browsers to open the link with.
FYI Safari has an option to open the current web page in another browser. It is in menu bar near developer tools.
A: you can configure the edge browser such way- but i couldnt found any solution for other browsers
<a href="microsoft-edge:https://meed.audiencevideo.com">May open on edge</a>' | unknown | |
d15184 | val | How about:
IEnumerable<T> sequence = GetSequenceFromSomewhere();
List<T> list = new List<T>(sequence);
Note that this is optimised for the situation where the sequence happens to be an IList<T> - it then uses IList<T>.CopyTo. It'll still be O(n) in most situations, but potentially a much faster O(n) than iterating :) (It also avoids any resizing as it creates it.)
A: You want to use the .AddRange method on generic List.
List<string> strings = new List<string>();
strings.AddRange(...);
.. or the constructor ..
new List<string>(...);
A: The List constructor is a good bet.
IEnumerable<T> enumerable = ...;
List<T> list = new List<T>(enumerable); | unknown | |
d15185 | val | It seems you want to send ctrl + c keys, which will copy some data in clipboard.. want to store that data in String variable..right?
You have to use Clipboard class to do so..See implementation below...
package resources;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class One {
@Test
public void getClipboardContents() {
String result = "";
System.setProperty("webdriver.chrome.driver", "C://WebDrivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com");
String copy = Keys.chord(Keys.CONTROL,Keys.chord("c"));
driver.findElement(By.linkText("Images")).sendKeys(copy);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
boolean hasTransferableText = (contents != null)
&& contents.isDataFlavorSupported(DataFlavor.stringFlavor);
if (hasTransferableText) {
try {
result = (String) contents.getTransferData(DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException | IOException ex) {
System.out.println(ex);
ex.printStackTrace();
}
}
System.out.println(result);
}
}
@Starlord ..modify locators as per your need.
A: @Gaurav Thanks for the code.. I have modified some part of the code.. now I am getting what i want exactly
public void getClipboardContents()
throws UnsupportedFlavorException, IOException {
String result = "google.com";
System.setProperty("webdriver.chrome.driver", "E:\\New folder\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.co.in/");
String copy = Keys.chord(Keys.CONTROL,Keys.chord("c"));
driver.findElement(By.xpath("//*[@id=\"lst-ib\"]")).sendKeys("google.com");
driver.findElement(By.xpath("//*[@id=\"lst-ib\"]")).sendKeys(Keys.CONTROL+"a");
driver.findElement(By.xpath("//*[@id=\"lst-ib\"]")).sendKeys(copy);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
String x = (String) contents.getTransferData(DataFlavor.stringFlavor);
System.out.println(x);
int a= result.length();
int b = x.length();
System.out.println(a);
System.out.println(b);
if(a<=b)
{
System.out.println("Matched Character length")
}else
{
System.out.println("Issue In Character length");
}
}
} | unknown | |
d15186 | val | I don't find any way to simulate browser update event. Here I use Edge as an example. As a workaround, you can download Edge Canary version to test which updates everyday.
Besides, if your device is Microsoft AD domain joined, you can also configure this policy to roll back Edge version, then update it when you test. | unknown | |
d15187 | val | Did you follow their guidelines for manual installation?
You should run
$ git init
(if your project is not initialized as a git repository)
and then
$ git submodule add https://github.com/Alamofire/Alamofire.git
(so that you can add it as a submodule)
I would also suggest you to delete the derived data, clean the project and then build it again. | unknown | |
d15188 | val | If you have a 2d array of strings (or anything that you are ok with toString-ing) for example:
const input = [
["555","123","345"],
[1, 2, 3],
[true, false, "foo"]
]
Then you can do something like this:
function toCsv(input) {
return input.map(row => row.join(',')).join('\n')
}
const csvString = toCsv(input)
Resulting in this string:
555,123,345
1,2,3
true,false,foo
If you just want to convert a single 1d array to csv, like in the example then:
const uniqueCounties = ["555","123","345"]
// If you want each value as a column
const csvAsSingleRow = uniqueCounties.join(',')
// If you want each value as a row
const csvAsSingleColumn = uniqueCounties.join('\n')
This gets more and more complicated if you want to include escaping, etc... In that case I'd recommend looking for a library that does this well. | unknown | |
d15189 | val | What's happening is that because your monitor is not a retina display and the device your simulating is it takes up more space on your monitor (notice the scroll bars).
You can scale the simulator so you can see everything at once without scrolling by clicking on Window > Scale > The percentage you want.
Aside from the scrolling issue, if the actual content doesn't display then you will need to either place it in a scroll view or set up your constraints to handle the different screen sizes. | unknown | |
d15190 | val | Here is an example of how you can do it. The ->with() method is not intended for this use, but you can just pass data in the route method instead, like so:
Route::get('/first-route', static function() {
return redirect()->route('second-route', ['data' => [1, 2, 3]]);
});
Route::get('/second-route', static function(\Illuminate\Http\Request $request) {
return view('test-view', ['data' => $request->input('data')]);
})->name('second-route');
Keep in mind that you are redirecting to another route, so you need the route you redirected to, to pass the data into the view. In this example, you can see that I pass [1, 2, 3] into second-route and then get the data via the request object. Then I pass that into the view in the second-route.
If I do a dd($request->input('data'); in second-route, I will get:
array:3 [
0 => "1"
1 => "2"
2 => "3"
]
So my best guess is that you never pass the data into the view, after the first route redirects to the next.
UPDATE:
Take a second and read the documentation about the ->with() method https://laravel.com/docs/7.x/redirects#redirecting-with-flashed-session-data and look at the PHPDoc of the code in RedirectResponse.php: Flash a piece of data to the session.
You can see here what the "flash" is used for: https://www.itsolutionstuff.com/post/laravel-5-implement-flash-messages-with-exampleexample.html
A: first time you need to call sellerPage method using this route.
Route::get('/seller/page','SellerController@sellerPage')->name('private_seller_report');
public function sellerPage()
{
$seller = Sellers::take(1)->latest()->get()->toArray();
return view('your.blade')->with(['seller' => $seller]);
} | unknown | |
d15191 | val | This question makes sense in the context of CPUs where the TLBs are
"manually" loaded and there are no predetermined page table
structures, like some models of MIPS, ARM, PowerPC.
So, some rough thoughts:
1G is 2^30 bytes or 2^18 = 256K 4K pages
Say, 4-byte entry per page, that's 1M for a single level page
table. Fast, but a bit wasteful on memory.
What can we do to reduce memory and still make it reasonably fast.
We need 18 bits per page frame number, cannot squeeze it in 2 bytes,
but can use 3-bytes per PTE, with 6 bits to spare to encode - access
rights, presence, COW, etc. That's 768K.
Instead of the whole page frame number we can keep only 16-bits of it,
with the remaining two determined by a 4-entry upper level page table
with a format like this:
*
*2 MSB of the physical page number
*21 bits for second level page table (30 bit address, aligned on 512K
boundary)
*spare bits
No place for per-page bits though, so lets move a few more address
bits to the upper level table to obtain
Second level page table entry (4K 2-byte entries = 8K)
*
*4 bits for random flags
*12 LSB of the page frame address
First level page table entry format (64 4-byte entries = 256 bytes):
*
*6 MSB of the page frame address
*17 bits for second level page table address (30-bit address aligned
at 8K)
*spare bits
A: Looks like an open end question to me. The main idea may be to know how much you know about memory and how much deep you can think of the cases to handle. Some of them could be:
*
*Pagination - How many pages you want to keep in memory for a process and how many on disk to optimize paging.
*Page Tables
*Security
*Others, if you can relate and think Of | unknown | |
d15192 | val | the code you shared got the ng-content usage backwards... the <custom-tabs-group> will be at the parent level and <ng-content> at the child level.
I tried 2 approaches:
*
*strategy #1: pass the content to the custom child inside the <mat-tab>... this worked
*strategy #2: pass the content to the custom child where <mat-tab> is inside the child... this didn't work
you can check the demo here
A: Actually i figured it out with some hack i don't know if its a good approch or not
custom-tabs.component.html
<div class="custom-tabs">
<mat-tab-group disableRipple>
<mat-tab *ngFor="let tab of tabsContentList" label="{{tab.label}}">
<div [innerHTML]="tab.htmlContent"></div>
</mat-tab>
</mat-tab-group>
</div>
custom-tabs-component.ts
import { DomSanitizer } from '@angular/platform-browser';
import { Component, OnInit, ViewEncapsulation, AfterContentInit, ContentChildren, Input, ViewChild, ElementRef, QueryList } from '@angular/core';
@Component({
selector: 'il-tabs-content',
template: `
<div #content>
<ng-content></ng-content>
</div>
`
,
})
export class TabsContentComponent implements OnInit {
@Input() label: String;
@ViewChild('content') set content(content: ElementRef) {
console.log("block three", content)
this.htmlContent = content;
if (this.htmlContent) {
this.htmlContent = this.htmlContent.nativeElement.innerHTML;
}
}
htmlContent: any;
constructor() { }
ngOnInit() {
}
}
@Component({
selector: 'il-tabs-group',
templateUrl: './tabs.component.html',
styleUrls: ['./tabs.component.css'],
encapsulation: ViewEncapsulation.None
})
export class TabsGroupComponent implements OnInit, AfterContentInit {
@ContentChildren(TabsContentComponent) tabsContentList: QueryList<TabsContentComponent>;
constructor(public sanitizer: DomSanitizer) { }
ngOnInit() {
}
ngAfterContentInit() {
this.tabsContentList.forEach((tabInstance) => {
var sanEle = this.sanitizer.bypassSecurityTrustHtml(tabInstance.htmlContent)
tabInstance.htmlContent = sanEle;
return tabInstance
})
}
}
usage
<il-tabs-group>
<il-tabs-content label="hello-1">
<h1>hello-1 content</h1>
</il-tabs-content>
<il-tabs-content label="hello-2">
<h1>hello-2 content</h1>
</il-tabs-content>
<il-tabs-content label="hello-3">
<h1>hello-3 content</h1>
<h2>extra content</h2>
</il-tabs-content>
</il-tabs-group>
i defined two components 'il-tabs-content' and 'li-tabs-group'. with this now i can use my own custom tabs build over angular material tabing with dynamic tabs. Anyone with better approch are welcome to share their ideas. thanks | unknown | |
d15193 | val | First of all, FirebaseStorage.getInstance() is a singleton, which will always create a single instance.
Furthermore, while Mauricio Gracia Gutierrez's will work, please see below a solution that uses Tasks#whenAllSuccess(Collection> tasks):
StorageReference imagesRef = FirebaseStorage.getInstance().getReference().child("Images/");
imagesRef.listAll().addOnCompleteListener(new OnCompleteListener<ListResult>() {
@Override
public void onComplete(@NonNull Task<ListResult> task) {
if (task.isSuccessful()) {
List<StorageReference> storageReferenceList = task.getResult().getItems();
List<Task<StorageMetadata>> tasks = new ArrayList<>();
storageReferenceList.forEach(item ->
tasks.add(item.getMetadata())
);
Tasks.whenAllSuccess(tasks).addOnSuccessListener(new OnSuccessListener<List<Object>>() {
@Override
public void onSuccess(List<Object> objects) {
for (Object object : objects) {
String title = ((StorageMetadata) object).getCustomMetadata("title");
Log.d("TAG", title);
}
}
});
} else {
Log.d(TAG, task.getException().getMessage()); //Never ignore potential errors!
}
}
});
In this way, you'll wait until you have a List full of titles.
A: You can create a backend API method that returns the list of titles for you in a single call
I know now that your code was demostration purposes only but....
*
*your code says task.getResult().getItems().get(0) meaning that only the first item is being used 150 times
*Calling task.getResult().getItems() inside the for, means that you are calling something that only needs to be called once 150 times
*Using harcoded 150 instead of the items.length is not a good idea
When you see that your code cumbersome or hard to read, follow the "Single Responsability" to split it into simpler methods.
In the code below I'm using type "Item" because I dont now the name of the type returned by task.getResult().getItems()
void getAllImagesMetadata() {
FirebaseStorage.getInstance().getReference().child("Images/").listAll().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Item []items = task.getResult().getItems() ;
for (int i = 0; i < items.length ; i++) {
title[i] = getTitle(items[i] ;
}
} else {
//Handle error
}
// Make sure the connection to get list of all items is closed here
}
string getTitle(Item item) {
string title ;
item.getMetadata().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
title = task.getResult().getCustomMetadata("title");
} else {
//Handle error
}
// Make sure the connection to get the metada is closed here
return title ;
} | unknown | |
d15194 | val | From the error message one can see that your URL is a file URL:
file:///http:/i.imgur.com/rfw7jrU.gif
and error -1100 is kCFURLErrorFileDoesNotExist (see CFNetwork Error Codes Reference).
You should replace
NSURL(fileURLWithPath: urlString)
by
NSURL(string: urlString)
// Swift 3+:
URL(string: urlString) | unknown | |
d15195 | val | Is there a difference with doing it this way?
No, both your examples do the exact same thing.
Promise.resolve and Promise.reject are simply static methods on the Promise Class that help you avoid constructing a whole Promise when you don't really need to.
A:
Is there a difference in the timing when each will be resolved?
No difference. The Promise executor (the callback you pass to new Promise()) is called immediately and synchronously. So, in BOTH cases, you are immediately and synchronously returning an already resolved promise and all the code in your function has already executed.
There should be no meaningful difference in execution timing. Of course, one might take slightly different number of CPU cycles to execute, but both have the exact same outcome and both immediately return a promise that is already resolved so there should be no difference to the calling code at all.
Promise.resolve() is just meant as a more compact (and probably more efficient) means of creating an already resolved promise.
Does Option 1 release control after all the work is done, and Option 2 release control as soon as the function is called?
They both return when all your work is done and they return an already resolved promise. This is because the executor callback to new Promise() is called synchronously (before your function returns).
I feel like this has root in the fact I don't fully understand the event loop. Thanks in advance for helping me understand this.
In this particular circumstance, all your code is run synchronously so there is no particular involvement of the event loop. The returnPromise() function returns (in both cases) when your code in the function is done executing synchronously. There is no async code here.
The event loop gets involved when you do .then() on the returned promise because even though the promise (in both cases) is already resolved, the .then() handler gets queued in the event queue and does not run until the rest of your Javascript after your .then() handler is done executing.
console.log("1");
returnPromise().then(function() {
console.log("2");
});
console.log("3");
This will generate identical output results:
1
3
2
with both versions of your returnPromise() function because .then() handlers are queued until the next tick of the event loop (e.g. after the rest of your current Javascript thread of execution is done). | unknown | |
d15196 | val | The int range issue is because you have an int literal. Use a double literal by postfixing 'd':
public static void main(String[] args) {
assignDoubleToInt(2147483646); // One less than the maximum value an int can hold
assignDoubleToInt(2147483647); // The maximum value an int can hold
assignDoubleToInt(2147483648d);// One greater than the maximum value an int can hold. Causes error and does not
// run.
}
I believe your equality test should be <=, also: "if the value in d is not larger than the maximum value for an int" - so if it is EQUAL to the maximum value for an int, it's valid:
public static void assignDoubleToInt(double d) {
int i = 0;
if (d <= Integer.MAX_VALUE)
i = (int) d;
System.out.println(i);
}
A:
Integer.MAX_VALUE holds 2147483647. I am assuming this is the maximum value an int can hold?
Yes.
throws "The literal 2147483648 of type int is out of range."
You can't create an int literal representing a number outside of the int range, so 2147483647 is legal but 2147483648 is not. If you want a larger integer literal, use a long literal, with the letter L appended: 2147483648L, or a double literal with a decimal point (or D appended): 2147483648.0 (or 2147483648D).
is not the proper way to do this.
The comparison d < Integer.MAX_VALUE is legal and correct, because Integer.MAX_VALUE will be widened to a double for the comparison, and a double can be (much) larger in value than Integer.MAX_VALUE. You just need to make sure you can pass the proper value in as detailed above.
(As noted in a comment above, it should be d <= Integer.MAX_VALUE, with <=.) | unknown | |
d15197 | val | I think what you want is a left join, because you want all the records of listing table and a few from c_profile table.
SELECT c_profile.c_name,
c_profile.logo,
c_profile.email,
listing.id,
listing.title,
listing.type,
listing.job_desc,
listing.c_id,
listing.time,
listing.vote_up
FROM listing
LEFT JOIN c_profile ON c_uid=c_id
this way you keep all records for listing and only join where you can find a matching c_profile
A: SELECT c_profile.c_name,c_profile.logo, c_profile.email, listing.id, listing.title, listing.type,listing.job_desc,listing.c_id, listing.time, listing.vote_up from listing left join c_profile ON c_profile.c_uid=listing .c_id | unknown | |
d15198 | val | I changed html a little bit:
<div id="result" style="background-color: red;">
<img id="photo" src="assets/images/audi.png"/>
<canvas id="canvas"></canvas>
</div>
And I used HTML2Canvas library, which takes a screenshot of the whatever you want and save it as image.
The javascript is as follows:
function upload_to_server(canvasData){
return fetch(api_url, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({photo: canvasData})
}).then(function (value) {
if(value.ok){
return value.json().then(function (response) {
// Do something with response
})
}
}).catch(function (reason) {
// Handle error
})
}
function onSaveChanges(){
save_button_label.classList.add('hide');
save_button_spinner.classList.remove('hide');
html2canvas(document.getElementById("result")).then(function(canvas) {
var canvasData = canvas.toDataURL("image/" + image_type + "");
upload_to_server(canvasData)
});
}
I hope that it will help someone. | unknown | |
d15199 | val | Let's assume that each cluster can be described with the following attributes:
@Getter
@Setter
public class KafkaCluster {
private String beanName;
private List<String> bootstrapServers;
}
For example, two clusters are defined in the application.properties:
kafka.clusters[0].bean-name=cluster1
kafka.clusters[0].bootstrap-servers=CLUSTER_1_URL
kafka.clusters[1].bean-name=cluster2
kafka.clusters[1].bootstrap-servers=CLUSTER_2_URL
Those properties are needed before beans are instantiated, to register KafkaTemplate beans' definitions, which makes @ConfigurationProperties unsuitable for this case. Instead, Binder API is used to bind them programmatically.
KafkaTemplate beans' definitions can be registered in the implementation of BeanDefinitionRegistryPostProcessor interface.
public class KafkaTemplateDefinitionRegistrar implements BeanDefinitionRegistryPostProcessor {
private final List<KafkaCluster> clusters;
public KafkaTemplateDefinitionRegistrar(Environment environment) {
clusters= Binder.get(environment)
.bind("kafka.clusters", Bindable.listOf(KafkaCluster.class))
.orElseThrow(IllegalStateException::new);
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
clusters.forEach(cluster -> {
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(KafkaTemplate.class);
beanDefinition.setInstanceSupplier(() -> kafkaTemplate(cluster));
registry.registerBeanDefinition(cluster.getBeanName(), beanDefinition);
});
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
public ProducerFactory<String, String> producerFactory(KafkaCluster kafkaCluster) {
Map<String, Object> configProps = new HashMap<>();
configProps.put(
ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,
kafkaCluster.getBootstrapServers());
configProps.put(
ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
StringSerializer.class);
configProps.put(
ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
StringSerializer.class);
return new DefaultKafkaProducerFactory<>(configProps);
}
public KafkaTemplate<String, String> kafkaTemplate(KafkaCluster kafkaCluster) {
return new KafkaTemplate<>(producerFactory(kafkaCluster));
}
}
Configuration class for the KafkaTemplateDefinitionRegistrar bean:
@Configuration
public class KafkaTemplateDefinitionRegistrarConfiguration {
@Bean
public static KafkaTemplateDefinitionRegistrar beanDefinitionRegistrar(Environment environment) {
return new KafkaTemplateDefinitionRegistrar(environment);
}
}
Additionally, exclude KafkaAutoConfiguration in the main class to prevent creating the default KafkaTemplate bean. This is probably not the best way because all the other KafkaAutoConfiguration beans are not created in that case.
@SpringBootApplication(exclude={KafkaAutoConfiguration.class})
Finally, below is a simple test that proves the existence of two KafkaTemplate beans.
@SpringBootTest
class SpringBootApplicationTest {
@Autowired
List<KafkaTemplate<String,String>> kafkaTemplates;
@Test
void kafkaTemplatesSizeTest() {
Assertions.assertEquals(kafkaTemplates.size(), 2);
}
}
For reference: Create N number of beans with BeanDefinitionRegistryPostProcessor, Spring Boot Dynamic Bean Creation From Properties File | unknown | |
d15200 | val | Your postdecrement operator is wrong, it should not return reference to *this. As you can see here: https://en.cppreference.com/w/cpp/language/operator_incdec its declaration is :
T T::operator--(int);
Post-increment and post-decrement creates a copy of the object, increments or decrements the value of the object and returns the copy from before the increment or decrement. | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.