You should set responseType: ResponseContentType.Blob
in your GET-Request settings, because so you can get your image as blob and convert it later da base64-encoded source. You code above is not good. If you would like to do this correctly, then create separate service to get images from API. Beacuse it ism't good to call HTTP-Request in components.
Here is an working example:
Create image.service.ts
and put following code:
Angular 4:
getImage(imageUrl: string): Observable<File> {
return this.http
.get(imageUrl, { responseType: ResponseContentType.Blob })
.map((res: Response) => res.blob());
}
Angular 5+:
getImage(imageUrl: string): Observable<Blob> {
return this.httpClient.get(imageUrl, { responseType: 'blob' });
}
Important: Since Angular 5+ you should use the new HttpClient
.
The new HttpClient
returns JSON by default. If you need other response type, so you can specify that by setting responseType: 'blob'
. Read more about that here.
Now you need to create some function in your image.component.ts
to get image and show it in html.
For creating an image from Blob you need to use JavaScript's FileReader
.
Here is function which creates new FileReader
and listen to FileReader's load-Event. As result this function returns base64-encoded image, which you can use in img src-attribute:
imageToShow: any;
createImageFromBlob(image: Blob) {
let reader = new FileReader();
reader.addEventListener("load", () => {
this.imageToShow = reader.result;
}, false);
if (image) {
reader.readAsDataURL(image);
}
}
Now you should use your created ImageService
to get image from api. You should to subscribe to data and give this data to createImageFromBlob
-function. Here is an example function:
getImageFromService() {
this.isImageLoading = true;
this.imageService.getImage(yourImageUrl).subscribe(data => {
this.createImageFromBlob(data);
this.isImageLoading = false;
}, error => {
this.isImageLoading = false;
console.log(error);
});
}
Now you can use your imageToShow
-variable in HTML template like this:
<img [src]="imageToShow"
alt="Place image title"
*ngIf="!isImageLoading; else noImageFound">
<ng-template #noImageFound>
<img src="fallbackImage.png" alt="Fallbackimage">
</ng-template>
I hope this description is clear to understand and you can use it in your project.
See the working example for Angular 5+ here.
If you're testing firebase app locally then you need to point functions to localhost
instead of cloud. By default, firebase serve
or firebase emulators:start
points the functions to server instead of localhost when you use it on your web app.
Add below script in html head after firebase init script:
<script>
firebase.functions().useFunctionsEmulator('http://localhost:5001')
</script>
Make sure to remove this snippet when deploying code to server.
"Chrome violations" don't represent errors in either Chrome or your own web app. They are instead warnings to help you improve your app. In this case, Long running JavaScript
and took 83ms of runtime
are alerting you there's probably an opportunity to speed up your script.
("Violation" is not the best terminology; it's used here to imply the script "violates" a pre-defined guideline, but "warning" or similar would be clearer. These messages first appeared in Chrome in early 2017 and should ideally have a "More info" prompt to elaborate on the meaning and give suggested actions to the developer. Hopefully those will be added in the future.)
From This page, the container dies after running everything correctly but crashes because all the commands ended. Either you make your services run on the foreground, or you create a keep alive script. By doing so, Kubernetes will show that your application is running. We have to note that in the Docker
environment, this problem is not encountered. It is only Kubernetes that wants a running app.
Update (an example):
Here's how to avoid CrashLoopBackOff, when launching a Netshoot container:
kubectl run netshoot --image nicolaka/netshoot -- sleep infinity
When your app and the libraries it references exceed 65,536 methods, you encounter a build error that indicates your app has reached the limit of the Android build architecture
To avoid this limitation you have to configure your app for multidex
If your minSdkVersion is set to 21 or higher, all you need to do is set multiDexEnabled to true in your module-level build.gradle file, as shown here:
android { defaultConfig { ... minSdkVersion 21 multiDexEnabled true } ... }
Else, if your minSdkVersion is set to 20 or lower, then you must use the multidex support library as follows:
1.Modify the module-level build.gradle file to enable multidex and add the multidex library as a dependency, as shown here:
android { defaultConfig { ... minSdkVersion 15 multiDexEnabled true } ... } dependencies { implementation 'com.android.support:multidex:1.0.3' }
2.Depending on whether you override the Application class, perform one of the following:
- If you do not override the Application class, edit your manifest file to set android:name in the tag as follows:
<application android:name="android.support.multidex.MultiDexApplication" > ... </application>
- Else If you do override the Application class, change it to extend MultiDexApplication (if possible) as follows:
public class MyApplication extends MultiDexApplication { ... }
- Else you do override the Application class but it's not possible to change the base class, then you can instead override the attachBaseContext() method and call MultiDex.install(this) to enable multidex:
public class MyApplication extends SomeOtherApplication { @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); } }
You can use these functions to brutally remove everything Docker related:
removecontainers() {
docker stop $(docker ps -aq)
docker rm $(docker ps -aq)
}
armageddon() {
removecontainers
docker network prune -f
docker rmi -f $(docker images --filter dangling=true -qa)
docker volume rm $(docker volume ls --filter dangling=true -q)
docker rmi -f $(docker images -qa)
}
You can add those to your ~/Xrc
file, where X is your shell interpreter (~/.bashrc
if you're using bash) file and reload them via executing source ~/Xrc
. Also, you can just copy paste them to the console and afterwards (regardless the option you took before to get the functions ready) just run:
armageddon
It's also useful for just general Docker clean up. Have in mind that this will also remove your images, not only your containers (either running or not) and your volumes of any kind.
for specific tag name
$ docker images --filter reference='<REPOSITORY>:TAG'
for "like clause" tagname:my_image_tag --> start my_ima*
$ docker images --filter reference='<REPOSITORY>:my_ima*'
if you want to someting "the image" for example delete all images tag started "my_ima" try this
docker rmi -f $(docker images -q --filter reference='myreponame:my_ima*')
I was getting the same issue and found that OpenSSH service was not running and it was causing the issue. After starting the SSH service it worked.
To check if SSH service is running or not:
ssh localhost
To start the service, if OpenSSH is already installed:
sudo /etc/init.d/ssh start
Your mock is raising the exception just fine, but the error.resp.status
value is missing. Rather than use return_value
, just tell Mock
that status
is an attribute:
barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
Additional keyword arguments to Mock()
are set as attributes on the resulting object.
I put your foo
and bar
definitions in a my_tests
module, added in the HttpError
class so I could use it too, and your test then can be ran to success:
>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
... barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
... result = my_test.foo()
...
404 -
>>> result is None
True
You can even see the print '404 - %s' % error.message
line run, but I think you wanted to use error.content
there instead; that's the attribute HttpError()
sets from the second argument, at any rate.
Chiming in to recommend the use of the xmltodict library. It handled your xml text pretty well and I've used it for ingesting an xml file with almost a million records.
If you want to set the column you filter on as a new index, you could also consider to use .filter
; if you want to keep it as a separate column then str.contains
is the way to go.
Let's say you have
df = pd.DataFrame({'vals': [1, 2, 3, 4, 5], 'ids': [u'aball', u'bball', u'cnut', u'fball', 'ballxyz']})
ids vals
0 aball 1
1 bball 2
2 cnut 3
3 fball 4
4 ballxyz 5
and your plan is to filter all rows in which ids
contains ball
AND set ids
as new index, you can do
df.set_index('ids').filter(like='ball', axis=0)
which gives
vals
ids
aball 1
bball 2
fball 4
ballxyz 5
But filter
also allows you to pass a regex, so you could also filter only those rows where the column entry ends with ball
. In this case you use
df.set_index('ids').filter(regex='ball$', axis=0)
vals
ids
aball 1
bball 2
fball 4
Note that now the entry with ballxyz
is not included as it starts with ball
and does not end with it.
If you want to get all entries that start with ball
you can simple use
df.set_index('ids').filter(regex='^ball', axis=0)
yielding
vals
ids
ballxyz 5
The same works with columns; all you then need to change is the axis=0
part. If you filter based on columns, it would be axis=1
.
In addition to all the answers, if you happen to receive in response text/html
while you've expected something else (i.e. application/json
), it may suggest that an error occurred on the server side (say 404) and the error page was returned instead of your data.
So it happened in my case. Hope it will save somebody's time.
For Arch Linux try this :
sudo vboxreload
Note that ng-bind-html-unsafe is no longer suppported in rc 1.2. Use ng-bind-html instead. See: With ng-bind-html-unsafe removed, how do I inject HTML?
I think this one will answer your question :P
$url="https://.../api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=??desc&limit=1&grab_content&content_limit=1";
Using cURL
// Initiate curl
$ch = curl_init();
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
var_dump(json_decode($result, true));
Using file_get_contents
$result = file_get_contents($url);
// Will dump a beauty json :3
var_dump(json_decode($result, true));
Accessing
$array["threads"][13/* thread id */]["title"/* thread key */]
And
$array["threads"][13/* thread id */]["content"/* thread key */]["content"][23/* post id */]["message" /* content key */];
The best approach is using a lambda within "array_walk" native function to make the required changes:
array_walk($data, function (&$value, $key) {
if($key == 'transaction_date'){
$value = date('d/m/Y', $value);
}
});
The value is updated in the array as it's passed with as a reference "&".
An update to munsellj's update..
I got this working in development just by adding localhost:3000 to the 'Website URL' option and leaving the App Domains box blank. As munsellj mentioned, make sure you've added a website platform.
I've changed the recursion to iteration.
def MovingTheBall(listOfBalls,position,numCell):
while 1:
stop=1
positionTmp = (position[0]+choice([-1,0,1]),position[1]+choice([-1,0,1]),0)
for i in range(0,len(listOfBalls)):
if positionTmp==listOfBalls[i].pos:
stop=0
if stop==1:
if (positionTmp[0]==0 or positionTmp[0]>=numCell or positionTmp[0]<=-numCell or positionTmp[1]>=numCell or positionTmp[1]<=-numCell):
stop=0
else:
return positionTmp
Works good :D
Try changing any temporary file. Like just remove any space or add space and then commit and push that file.
git add 'temporary_change_file'
git commit -m "git issue resolving"
git push origin develop
And then try git pull,
git pull origin develop
Hope this might help you.
dynamic dynJson = JsonConvert.DeserializeObject(json);
foreach (var item in dynJson)
{
Console.WriteLine("{0} {1} {2} {3}\n", item.id, item.displayName,
item.slug, item.imageUrl);
}
or
var list = JsonConvert.DeserializeObject<List<MyItem>>(json);
public class MyItem
{
public string id;
public string displayName;
public string name;
public string slug;
public string imageUrl;
}
I think the documentation is reasonably helpful!
If you read it again, it says that adding open graph elements on your website will make your website act as a facebook page and you'll get the ability to publish updates to them etc.
So I think it's up to you - you can either just have a page with no OG elements, which is less work but also less 'rewarding' for you.
If you do use og, then set type to: blog
Finally: fb:admins
or fb:app_id
- A comma-separated list of either the Facebook IDs of page administrators or a Facebook Platform application ID. At a minimum, include only your own Facebook ID.
So just put your own fbid in there. As a tip, you can easily get this by looking at the url of your profile photo on facebook.
here is another solution...
System.IO.Stream st = new System.IO.StreamReader (picturePath).BaseStream;
byte[] buffer = new byte[4096];
System.IO.MemoryStream m = new System.IO.MemoryStream ();
while (st.Read (buffer,0,buffer.Length) > 0) {
m.Write (buffer, 0, buffer.Length);
}
imgView.Tag = m.ToArray ();
st.Close ();
m.Close ();
hope it helps!
This is, in effect, a way to check whether the expression e can be evaluated to be 0, and if not, to fail the build.
The macro is somewhat misnamed; it should be something more like BUILD_BUG_OR_ZERO
, rather than ...ON_ZERO
. (There have been occasional discussions about whether this is a confusing name.)
You should read the expression like this:
sizeof(struct { int: -!!(e); }))
(e)
: Compute expression e
.
!!(e)
: Logically negate twice: 0
if e == 0
; otherwise 1
.
-!!(e)
: Numerically negate the expression from step 2: 0
if it was 0
; otherwise -1
.
struct{int: -!!(0);} --> struct{int: 0;}
: If it was zero, then we declare a struct with an anonymous integer bitfield that has width zero. Everything is fine and we proceed as normal.
struct{int: -!!(1);} --> struct{int: -1;}
: On the other hand, if it isn't zero, then it will be some negative number. Declaring any bitfield with negative width is a compilation error.
So we'll either wind up with a bitfield that has width 0 in a struct, which is fine, or a bitfield with negative width, which is a compilation error. Then we take sizeof
that field, so we get a size_t
with the appropriate width (which will be zero in the case where e
is zero).
Some people have asked: Why not just use an assert
?
keithmo's answer here has a good response:
These macros implement a compile-time test, while assert() is a run-time test.
Exactly right. You don't want to detect problems in your kernel at runtime that could have been caught earlier! It's a critical piece of the operating system. To whatever extent problems can be detected at compile time, so much the better.
I have written a small (de)serialization framework called any2any that helps doing complex transformations between two Python types.
In your case, I guess you want to transform from a dictionary (obtained with json.loads
) to an complex object response.education ; response.name
, with a nested structure response.education.id
, etc ...
So that's exactly what this framework is made for. The documentation is not great yet, but by using any2any.simple.MappingToObject
, you should be able to do that very easily. Please ask if you need help.
Use the Twitter Intent resource https://dev.twitter.com/web/tweet-button/web-intent
There are two options here.
One is to do an interactive rebase and edit the merge commit, redo the merge manually and continue the rebase.
Another is to use the --rebase-merges
option on git rebase
, which is described as follows from the manual:
By default, a rebase will simply drop merge commits from the todo list, and put the rebased commits into a single, linear branch. With --rebase-merges, the rebase will instead try to preserve the branching structure within the commits that are to be rebased, by recreating the merge commits. Any resolved merge conflicts or manual amendments in these merge commits will have to be resolved/re-applied manually."
Here's a simpler method, that requires neither events or timeouts. It does require jQuery, however.
Use jQuery.holdReady()
(docs)
So, immediately after your jQuery script, delay the ready event.
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$.holdReady( true ); // don't fire ready until told (ie when FB loaded)
</script>
Then, in your Facebook init function, release it:
window.fbAsyncInit = function() {
FB.init({
appId: '11111111111111',
cookie: true,
xfbml: false,
version: 'v2.4'
});
// release the ready event to execute
$.holdReady( false );
};
Then you can use the ready event as normal:
$(document).ready( myApp.init );
Your class MyClass
creates a new MyClassToBeTested
, instead of using your mock. My article on the Mockito wiki describes two ways of dealing with this.
You need to have
#include <string>
in the header file too.The forward declaration on it's own doesn't do enough.
Also strongly consider header guards for your header files to avoid possible future problems as your project grows. So at the top do something like:
#ifndef THE_FILE_NAME_H
#define THE_FILE_NAME_H
/* header goes in here */
#endif
This will prevent the header file from being #included multiple times, if you don't have such a guard then you can have issues with multiple declarations.
Try applying the clear:none
css attribute to the label.
.label {
clear:none;
}
To answer this question:
:40,50s/foo/bar/g
replace foo with bar in these lines between the 40th line and the 50th line(inclusive), when execute this command you can currently in any line.
:50,40s/foo/bar/g
also works, vim will ask you for comfirm and then do the replacement for you as if you have input the first command.
:,50s/foo/bar/g
replace foo with bar in these lines between the line you are currently in and the 50th line(inclusive). (if you are in a line AFTER the 50th line vim will ask for confirm again)
To clearity the difference between vim and the vrapper plugin of Eclipse:
Note that in varpper
:,50s/foo/bar/g
command will NOT work.
:50,40s/foo/bar/g
will work without asking for comfirmation.
(For Vrapper Version 0.74.0 or older).
When in the onclick
attribute you do not need to specify that it is Javascript.
<button type="button"
onclick="window.open('', '_self', ''); window.close();">Discard</button>
This should do it. In order to close it your page needs to be opened by the script, hence the window.open. Here is an article explaining this in detail:
If all else fails, you should also add a message asking the user to manually close the window, as there is no cross-browser solution for this, especially with older browsers such as IE 8.
To do this in t-sql, you can use the following system stored procedures to schedule a daily job. This example schedules daily at 1:00 AM. See Microsoft help for details on syntax of the individual stored procedures and valid range of parameters.
DECLARE @job_name NVARCHAR(128), @description NVARCHAR(512), @owner_login_name NVARCHAR(128), @database_name NVARCHAR(128);
SET @job_name = N'Some Title';
SET @description = N'Periodically do something';
SET @owner_login_name = N'login';
SET @database_name = N'Database_Name';
-- Delete job if it already exists:
IF EXISTS(SELECT job_id FROM msdb.dbo.sysjobs WHERE (name = @job_name))
BEGIN
EXEC msdb.dbo.sp_delete_job
@job_name = @job_name;
END
-- Create the job:
EXEC msdb.dbo.sp_add_job
@job_name=@job_name,
@enabled=1,
@notify_level_eventlog=0,
@notify_level_email=2,
@notify_level_netsend=2,
@notify_level_page=2,
@delete_level=0,
@description=@description,
@category_name=N'[Uncategorized (Local)]',
@owner_login_name=@owner_login_name;
-- Add server:
EXEC msdb.dbo.sp_add_jobserver @job_name=@job_name;
-- Add step to execute SQL:
EXEC msdb.dbo.sp_add_jobstep
@job_name=@job_name,
@step_name=N'Execute SQL',
@step_id=1,
@cmdexec_success_code=0,
@on_success_action=1,
@on_fail_action=2,
@retry_attempts=0,
@retry_interval=0,
@os_run_priority=0,
@subsystem=N'TSQL',
@command=N'EXEC my_stored_procedure; -- OR ANY SQL STATEMENT',
@database_name=@database_name,
@flags=0;
-- Update job to set start step:
EXEC msdb.dbo.sp_update_job
@job_name=@job_name,
@enabled=1,
@start_step_id=1,
@notify_level_eventlog=0,
@notify_level_email=2,
@notify_level_netsend=2,
@notify_level_page=2,
@delete_level=0,
@description=@description,
@category_name=N'[Uncategorized (Local)]',
@owner_login_name=@owner_login_name,
@notify_email_operator_name=N'',
@notify_netsend_operator_name=N'',
@notify_page_operator_name=N'';
-- Schedule job:
EXEC msdb.dbo.sp_add_jobschedule
@job_name=@job_name,
@name=N'Daily',
@enabled=1,
@freq_type=4,
@freq_interval=1,
@freq_subday_type=1,
@freq_subday_interval=0,
@freq_relative_interval=0,
@freq_recurrence_factor=1,
@active_start_date=20170101, --YYYYMMDD
@active_end_date=99991231, --YYYYMMDD (this represents no end date)
@active_start_time=010000, --HHMMSS
@active_end_time=235959; --HHMMSS
I had the same problems.
I solved it verifying that IE8 was not configured correctly to reach the SRC URL.
I changed this, it works right.
Objects in JavaScript are collections of unordered properties. Objects are hashtables.
If you want your properties to be in alphabetical order, one possible solution would be to create an index for your properties in a separate array. Just a few hours ago, I answered a question on Stack Overflow which you may want to check out:
Here's a quick adaptation for your object1:
var obj = {
"set1": [1, 2, 3],
"set2": [4, 5, 6, 7, 8],
"set3": [9, 10, 11, 12]
};
var index = [];
// build the index
for (var x in obj) {
index.push(x);
}
// sort the index
index.sort(function (a, b) {
return a == b ? 0 : (a > b ? 1 : -1);
});
Then you would be able to do the following:
console.log(obj[index[1]]);
The answer I cited earlier proposes a reusable solution to iterate over such an object. That is unless you can change your JSON to as @Jacob Relkin suggested in the other answer, which could be easier.
1 You may want to use the hasOwnProperty()
method to ensure that the properties belong to your object and are not inherited from Object.prototype
.
Here's the YUI version if anyone's interested:
http://developer.yahoo.com/yui/docs/YAHOO.util.Number.html
var str = YAHOO.util.Number.format(12345, { thousandsSeparator: ',' } );
The main reason you'd do this is to decouple your code from a specific implementation of the interface. When you write your code like this:
List list = new ArrayList();
the rest of your code only knows that data is of type List
, which is preferable because it allows you to switch between different implementations of the List
interface with ease.
For instance, say you were writing a fairly large 3rd party library, and say that you decided to implement the core of your library with a LinkedList
. If your library relies heavily on accessing elements in these lists, then eventually you'll find that you've made a poor design decision; you'll realize that you should have used an ArrayList
(which gives O(1) access time) instead of a LinkedList
(which gives O(n) access time). Assuming you have been programming to an interface, making such a change is easy. You would simply change the instance of List
from,
List list = new LinkedList();
to
List list = new ArrayList();
and you know that this will work because you have written your code to follow the contract provided by the List
interface.
On the other hand, if you had implemented the core of your library using LinkedList list = new LinkedList()
, making such a change wouldn't be as easy, as there is no guarantee that the rest of your code doesn't make use of methods specific to the LinkedList
class.
All in all, the choice is simply a matter of design... but this kind of design is very important (especially when working on large projects), as it will allow you to make implementation-specific changes later without breaking existing code.
Slightly different approach:
MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add("HeaderName", "value");
headers.add("Content-Type", "application/json");
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpEntity<ObjectToPass> request = new HttpEntity<ObjectToPass>(objectToPass, headers);
restTemplate.postForObject(url, request, ClassWhateverYourControllerReturns.class);
They're nearly identical but bash
has more features – sh
is (more or less) an older subset of bash
.
sh
often means the original Bourne shell
, which predates bash
(Bourne *again* shell
), and was created in 1977. But, in practice, it may be better to think of it as a highly-cross-compatible shell compliant with the POSIX standard from 1992.
Scripts that start with #!/bin/sh
or use the sh
shell usually do so for backwards compatibility. Any unix/linux OS will have an sh
shell. On Ubuntu sh
often invokes dash
and on MacOS it's a special POSIX version of bash
. These shells may be preferred for standard-compliant behavior, speed or backwards compatibility.
bash
is newer than the original sh
, adds more features, and seeks to be backwards compatible with sh
. In theory, sh
programs should run in bash
. bash
is available on nearly all linux/unix machines and usually used by default – with the notable exception of MacOS defaulting to zsh
as of Catalina (10.15). FreeBSD, by default, does not come with bash
installed.
public function updtitle()
{
$data = array(
'table_name' => 'your_table_name_to_update', // pass the real table name
'id' => $this->input->post('id'),
'title' => $this->input->post('title')
);
$this->load->model('Updmodel'); // load the model first
if($this->Updmodel->upddata($data)) // call the method from the model
{
// update successful
}
else
{
// update not successful
}
}
public function upddata($data) {
extract($data);
$this->db->where('emp_no', $id);
$this->db->update($table_name, array('title' => $title));
return true;
}
The active record query is similar to
"update $table_name set title='$title' where emp_no=$id"
Outside of character classes, it is conventional not to escape hyphens. If I saw an escaped hyphen outside of a character class, that would suggest to me that it was written by someone who was not very comfortable with regexes.
Inside character classes, I don't think one way is conventional over the other; in my experience, it usually seems to be to put either first or last, as in [-._:]
or [._:-]
, to avoid the backslash; but I've also often seen it escaped instead, as in [._\-:]
, and I wouldn't call that unconventional.
Update: This answer may be incorrect or out of date. Please see comments for details.
I switched from @Inject
to @EJB
because @EJB
allows circular injection whereas @Inject
pukes on it.
Details: I needed @PostConstruct
to call an @Asynchronous
method but it would do so synchronously. The only way to make the asynchronous call was to have the original call a method of another bean and have it call back the method of the original bean. To do this each bean needed a reference to the other -- thus circular. @Inject
failed for this task whereas @EJB
worked.
You can use this:
SELECT COUNT(*) FROM (SELECT DISTINCT column_name FROM table_name) AS temp;
This is much faster than:
COUNT(DISTINCT column_name)
The following snippets test for the "not contains" condition, as exemplified in the sample pseudocode in the question. For a direct solution with explicit looping, do this:
boolean contains = false;
for (char c : charArray) {
if (c == 'q') {
contains = true;
break;
}
}
if (!contains) {
// do something
}
Another alternative, using the fact that String
provides a contains()
method:
if (!(new String(charArray).contains("q"))) {
// do something
}
Yet another option, this time using indexOf()
:
if (new String(charArray).indexOf('q') == -1) {
// do something
}
If you are using CentOS linux system the Maven local repositary will be:
/root/.m2/repository/
You can remove .m2 and build your maven project in dev tool will fix the issue.
Thanks Jim Lewis for his great answer and I would like to illustrate this solution by my function in Swift:
func getRandomLocation(forLocation location: CLLocation, withOffsetKM offset: Double) -> CLLocation {
let latDistance = (Double(arc4random()) / Double(UInt32.max)) * offset * 2.0 - offset
let longDistanceMax = sqrt(offset * offset - latDistance * latDistance)
let longDistance = (Double(arc4random()) / Double(UInt32.max)) * longDistanceMax * 2.0 - longDistanceMax
let lat: CLLocationDegrees = location.coordinate.latitude + latDistance / 110.574
let lng: CLLocationDegrees = location.coordinate.longitude + longDistance / (111.320 * cos(lat / .pi / 180))
return CLLocation(latitude: lat, longitude: lng)
}
In this function to convert distance I use following formulas:
latDistance / 110.574
longDistance / (111.320 * cos(lat / .pi / 180))
I think the reason it doesn't work has something to do with the fact that you have the right
position set, but not the left
.
If you manually set the left
to the current position, it seems to go:
Live example: http://jsfiddle.net/XqqtN/
var left = $('#coolDiv').offset().left; // Get the calculated left position
$("#coolDiv").css({left:left}) // Set the left to its calculated position
.animate({"left":"0px"}, "slow");
EDIT:
Appears as though Firefox behaves as expected because its calculated left
position is available as the correct value in pixels, whereas Webkit based browsers, and apparently IE, return a value of auto
for the left position.
Because auto
is not a starting position for an animation, the animation effectively runs from 0 to 0. Not very interesting to watch. :o)
Setting the left position manually before the animate as above fixes the issue.
If you don't like cluttering the landscape with variables, here's a nice version of the same thing that obviates the need for a variable:
$("#coolDiv").css('left', function(){ return $(this).offset().left; })
.animate({"left":"0px"}, "slow"); ?
Use ENUM in MySQL for true / false it gives and accepts the true / false values without any extra code.
ALTER TABLE `itemcategory` ADD `aaa` ENUM('false', 'true') NOT NULL DEFAULT 'false'
get_or_create
returns a tuple.
customer.source, created = Source.objects.get_or_create(name="Website")
you can use the following Bootstrap class with
<tr class="w-25">
</tr>
for more details check the following page https://getbootstrap.com/docs/4.1/utilities/sizing/
In case of lazy loading, you just need to import MatDialogModule in lazy loaded module. Then this module will be able to render entry component with its own imported MatDialogModule:
@NgModule({
imports:[
MatDialogModule
],
declarations: [
AppComponent,
LoginComponent,
DashboardComponent,
HomeComponent,
DialogResultExampleDialog
],
entryComponents: [DialogResultExampleDialog]
Consider using the HtmlManipulator Java class. You may need to add some items (not all entities are in the list).
The Apache Commons StringEscapeUtils as suggested by Kevin Hakanson did not work 100% for me; several entities like ‘ (left single quote) were translated into '222' somehow. I also tried org.jsoup, and had the same problem.
Just ran into this syntax problem on a CentOS 7 machine.
On a very old Ubuntu machine running mail
, the syntax for a nicely composed email is
echo -e "$body" | mail -s "$subject" -a "From: Sender Name <$sender>" "$recipient"
However on a CentOS 7 box which came with mailx
installed, it's quite different:
echo -e "$body" | mail -s "$subject" -S "from=Sender Name <$sender>" "$recipient"
Consulting man mail
indicates that -r
is deprecated and the 'From' sender address should now be set directly using -S "variable=value"
.
In these and subsequent examples, I'm defining
$sender
as"Sender Name <[email protected]>"
and$recipients
as"[email protected]"
as I do in my bash script.
You may then find, as I did, that when you try to generate the email's body content in your script at the point of sending the email, you encounter a strange behaviour where the email body is instead attached as a binary file ("ATT00001.bin", "application/octet-stream" or "noname", depending on client).
This behaviour is how Heirloom mailx handles unrecognised / control characters in text input. (More info: https://access.redhat.com/solutions/1136493, which itself references the mailx man page for the solution.)
To get around this, I used a method which pipes the generated output through tr
before passing to mail
, and also specifies the charset of the email:
echo -e "$body" | tr -d \\r | mail -s "$subject" -S "from=$sender" -S "sendcharsets=utf-8,iso-8859-1" "$recipients"
In my script, I'm also explicitly delaring the locale beforehand as it's run as a cronjob (and cron doesn't inherit environmental variables):
LANG="en_GB.UTF8" ; export LANG ;
(An alternate method of setting locales for cronjobs is discussed here)
More info on these workarounds via https://stackoverflow.com/a/29826988/253139 and https://stackoverflow.com/a/3120227/253139.
What you are looking for is a query with WITH
clause, if your dbms supports it. Then
WITH NewScores AS (
SELECT *
FROM Score
WHERE InsertedDate >= DATEADD(mm, -3, GETDATE())
)
SELECT
<and the rest of your query>
;
Note that there is no ;
in the first half. HTH.
If there is a failed merge, which is the most common reason for wanting to undo a git pull
, running git reset --merge
does exactly what one would expect: keep the fetched files, but undo the merge that git pull
attempted to merge. Then one can decide what to do without the clutter that git merge
sometimes generates. And it does not need one to find the exact commit ID which --hard
mentioned in every other answer requires.
Problem solved after I run those commands with sudo
The AS
keyword is to give an ALIAS name to your database table or to table column. In your example, both statement are correct but there are circumstance where AS clause is needed (though the AS
operator itself is optional), e.g.
SELECT salary * 2 AS "Double salary" FROM employee;
In this case, the Employee
table has a salary
column and we just want the double of the salary with a new name Double Salary
.
Sorry if my explanation is not effective.
Update based on your comment, you're right, my previous statement was invalid. The only reason I can think of is that the AS
clause has been in existence for long in the SQL world that it's been incorporated in nowadays RDMS for backward compatibility..
PHP runs on the server and Javascript runs on the client, so you can't set a PHP variable to equal a Javascript variable without sending the value to the server. You can, however, set a Javascript variable to equal a PHP variable:
<script type="text/javascript">
var foo = '<?php echo $foo ?>';
</script>
To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):
var variableToSend = 'foo';
$.post('file.php', {variable: variableToSend});
On your server, you would need to receive the variable sent in the post:
$variable = $_POST['variable'];
a.sort(function(a,b){return a - b})
These can be confusing.... check this link out.
When a source program is fed into the lexical analyzer, it begins by breaking up the characters into sequences of lexemes. The lexemes are then used in the construction of tokens, in which the lexemes are mapped into tokens. A variable called myVar would be mapped into a token stating <id, "num">, where "num" should point to the variable's location in the symbol table.
Shortly put:
An example includes:
x = a + b * 2
Which yields the lexemes: {x, =, a, +, b, *, 2}
With corresponding tokens: {<id, 0>, <=>, <id, 1>, <+>, <id, 2>, <*>, <id, 3>}
You should put your component between an enclosing tag, Which means:
// WRONG!
return (
<Comp1 />
<Comp2 />
)
Instead:
// Correct
return (
<div>
<Comp1 />
<Comp2 />
</div>
)
Edit: Per Joe Clay's comment about the Fragments API
// More Correct
return (
<React.Fragment>
<Comp1 />
<Comp2 />
</React.Fragment>
)
// Short syntax
return (
<>
<Comp1 />
<Comp2 />
</>
)
Follwoing [PhD EcE](https://stackoverflow.com/users/3818417/phd-ece) suggestion, I implemented the thread pool:
function_pool.h
#pragma once
#include <queue>
#include <functional>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <cassert>
class Function_pool
{
private:
std::queue<std::function<void()>> m_function_queue;
std::mutex m_lock;
std::condition_variable m_data_condition;
std::atomic<bool> m_accept_functions;
public:
Function_pool();
~Function_pool();
void push(std::function<void()> func);
void done();
void infinite_loop_func();
};
function_pool.cpp
#include "function_pool.h"
Function_pool::Function_pool() : m_function_queue(), m_lock(), m_data_condition(), m_accept_functions(true)
{
}
Function_pool::~Function_pool()
{
}
void Function_pool::push(std::function<void()> func)
{
std::unique_lock<std::mutex> lock(m_lock);
m_function_queue.push(func);
// when we send the notification immediately, the consumer will try to get the lock , so unlock asap
lock.unlock();
m_data_condition.notify_one();
}
void Function_pool::done()
{
std::unique_lock<std::mutex> lock(m_lock);
m_accept_functions = false;
lock.unlock();
// when we send the notification immediately, the consumer will try to get the lock , so unlock asap
m_data_condition.notify_all();
//notify all waiting threads.
}
void Function_pool::infinite_loop_func()
{
std::function<void()> func;
while (true)
{
{
std::unique_lock<std::mutex> lock(m_lock);
m_data_condition.wait(lock, [this]() {return !m_function_queue.empty() || !m_accept_functions; });
if (!m_accept_functions && m_function_queue.empty())
{
//lock will be release automatically.
//finish the thread loop and let it join in the main thread.
return;
}
func = m_function_queue.front();
m_function_queue.pop();
//release the lock
}
func();
}
}
main.cpp
#include "function_pool.h"
#include <string>
#include <iostream>
#include <mutex>
#include <functional>
#include <thread>
#include <vector>
Function_pool func_pool;
class quit_worker_exception : public std::exception {};
void example_function()
{
std::cout << "bla" << std::endl;
}
int main()
{
std::cout << "stating operation" << std::endl;
int num_threads = std::thread::hardware_concurrency();
std::cout << "number of threads = " << num_threads << std::endl;
std::vector<std::thread> thread_pool;
for (int i = 0; i < num_threads; i++)
{
thread_pool.push_back(std::thread(&Function_pool::infinite_loop_func, &func_pool));
}
//here we should send our functions
for (int i = 0; i < 50; i++)
{
func_pool.push(example_function);
}
func_pool.done();
for (unsigned int i = 0; i < thread_pool.size(); i++)
{
thread_pool.at(i).join();
}
}
For all Objective C lovers that need this in a UI-Test:
-(void) clearTextField:(XCUIElement*) textField{
NSString* currentInput = (NSString*) textField.value;
NSMutableString* deleteString = [NSMutableString new];
for(int i = 0; i < currentInput.length; ++i) {
[deleteString appendString: [NSString stringWithFormat:@"%c", 8]];
}
[textField typeText:deleteString];
}
This is possible in Java 9.
Stream.generate(() -> null)
.takeWhile(x -> iterator.hasNext())
.map(n -> iterator.next())
.forEach(System.out::println);
tf.initialize_all_variables()
is deprecated. Instead initialize tensorflow variables with:
tf.global_variables_initializer()
A common example usage is:
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
the solution to the typescript:
Step1:
npm install jquery
npm install --save-dev @types/jquery
step2: in Angular.json add:
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
]
or in index.html add:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
step3: in *.component.ts where you want to use jquery
import * as $ from 'jquery'; // dont need "declare let $"
Then you can use jquery the same as javaScript. This way, VScode supports auto-suggestion by Typescript
Tables are iffy (at least, in IE) when it comes to fixing heights and not wrapping text. I think you'll find that the only solution is to put the text inside a div
element, like so:
td.container > div {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
overflow:hidden;_x000D_
}_x000D_
td.container {_x000D_
height: 20px;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td class="container">_x000D_
<div>This is a long line of text designed not to wrap _x000D_
when the container becomes too small.</div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
This way, the div
's height is that of the containing cell and the text cannot grow the div
, keeping the cell/row the same height no matter what the window size is.
Here is a pure C# version that should work with all versions of .NET (including .NET Core, .NET 5, WPF, Winforms, etc.) and uses Windows Vista (and higher) IFileDialog interface with the FOS_PICKFOLDERS options so it has the nice folder picker Windows standard UI.
I have also added WPF's Window
type support but this is optional.
usage:
var dlg = new FolderPicker();
dlg.InputPath = @"c:\windows\system32";
if (dlg.ShowDialog() == true)
{
MessageBox.Show(dlg.ResultPath);
}
code:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Windows; // for WPF support
using System.Windows.Interop; // for WPF support
public class FolderPicker
{
public virtual string ResultPath { get; protected set; }
public virtual string ResultName { get; protected set; }
public virtual string InputPath { get; set; }
public virtual bool ForceFileSystem { get; set; }
public virtual string Title { get; set; }
public virtual string OkButtonLabel { get; set; }
public virtual string FileNameLabel { get; set; }
protected virtual int SetOptions(int options)
{
if (ForceFileSystem)
{
options |= (int)FOS.FOS_FORCEFILESYSTEM;
}
return options;
}
// for WPF support
public bool? ShowDialog(Window owner = null, bool throwOnError = false)
{
owner ??= Application.Current.MainWindow;
return ShowDialog(owner != null ? new WindowInteropHelper(owner).Handle : IntPtr.Zero, throwOnError);
}
// for all .NET
public virtual bool? ShowDialog(IntPtr owner, bool throwOnError = false)
{
var dialog = (IFileOpenDialog)new FileOpenDialog();
if (!string.IsNullOrEmpty(InputPath))
{
if (CheckHr(SHCreateItemFromParsingName(InputPath, null, typeof(IShellItem).GUID, out var item), throwOnError) != 0)
return null;
dialog.SetFolder(item);
}
var options = FOS.FOS_PICKFOLDERS;
options = (FOS)SetOptions((int)options);
dialog.SetOptions(options);
if (Title != null)
{
dialog.SetTitle(Title);
}
if (OkButtonLabel != null)
{
dialog.SetOkButtonLabel(OkButtonLabel);
}
if (FileNameLabel != null)
{
dialog.SetFileName(FileNameLabel);
}
if (owner == IntPtr.Zero)
{
owner = Process.GetCurrentProcess().MainWindowHandle;
if (owner == IntPtr.Zero)
{
owner = GetDesktopWindow();
}
}
var hr = dialog.Show(owner);
if (hr == ERROR_CANCELLED)
return null;
if (CheckHr(hr, throwOnError) != 0)
return null;
if (CheckHr(dialog.GetResult(out var result), throwOnError) != 0)
return null;
if (CheckHr(result.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEPARSING, out var path), throwOnError) != 0)
return null;
ResultPath = path;
if (CheckHr(result.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEEDITING, out path), false) == 0)
{
ResultName = path;
}
return true;
}
private static int CheckHr(int hr, bool throwOnError)
{
if (hr != 0)
{
if (throwOnError)
Marshal.ThrowExceptionForHR(hr);
}
return hr;
}
[DllImport("shell32")]
private static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IBindCtx pbc, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, out IShellItem ppv);
[DllImport("user32")]
private static extern IntPtr GetDesktopWindow();
#pragma warning disable IDE1006 // Naming Styles
private const int ERROR_CANCELLED = unchecked((int)0x800704C7);
#pragma warning restore IDE1006 // Naming Styles
[ComImport, Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")] // CLSID_FileOpenDialog
private class FileOpenDialog
{
}
[ComImport, Guid("42f85136-db7e-439c-85f1-e4075d135fc8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IFileOpenDialog
{
[PreserveSig] int Show(IntPtr parent); // IModalWindow
[PreserveSig] int SetFileTypes(); // not fully defined
[PreserveSig] int SetFileTypeIndex(int iFileType);
[PreserveSig] int GetFileTypeIndex(out int piFileType);
[PreserveSig] int Advise(); // not fully defined
[PreserveSig] int Unadvise();
[PreserveSig] int SetOptions(FOS fos);
[PreserveSig] int GetOptions(out FOS pfos);
[PreserveSig] int SetDefaultFolder(IShellItem psi);
[PreserveSig] int SetFolder(IShellItem psi);
[PreserveSig] int GetFolder(out IShellItem ppsi);
[PreserveSig] int GetCurrentSelection(out IShellItem ppsi);
[PreserveSig] int SetFileName([MarshalAs(UnmanagedType.LPWStr)] string pszName);
[PreserveSig] int GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);
[PreserveSig] int SetTitle([MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
[PreserveSig] int SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string pszText);
[PreserveSig] int SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
[PreserveSig] int GetResult(out IShellItem ppsi);
[PreserveSig] int AddPlace(IShellItem psi, int alignment);
[PreserveSig] int SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);
[PreserveSig] int Close(int hr);
[PreserveSig] int SetClientGuid(); // not fully defined
[PreserveSig] int ClearClientData();
[PreserveSig] int SetFilter([MarshalAs(UnmanagedType.IUnknown)] object pFilter);
[PreserveSig] int GetResults([MarshalAs(UnmanagedType.IUnknown)] out object ppenum);
[PreserveSig] int GetSelectedItems([MarshalAs(UnmanagedType.IUnknown)] out object ppsai);
}
[ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IShellItem
{
[PreserveSig] int BindToHandler(); // not fully defined
[PreserveSig] int GetParent(); // not fully defined
[PreserveSig] int GetDisplayName(SIGDN sigdnName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszName);
[PreserveSig] int GetAttributes(); // not fully defined
[PreserveSig] int Compare(); // not fully defined
}
#pragma warning disable CA1712 // Do not prefix enum values with type name
private enum SIGDN : uint
{
SIGDN_DESKTOPABSOLUTEEDITING = 0x8004c000,
SIGDN_DESKTOPABSOLUTEPARSING = 0x80028000,
SIGDN_FILESYSPATH = 0x80058000,
SIGDN_NORMALDISPLAY = 0,
SIGDN_PARENTRELATIVE = 0x80080001,
SIGDN_PARENTRELATIVEEDITING = 0x80031001,
SIGDN_PARENTRELATIVEFORADDRESSBAR = 0x8007c001,
SIGDN_PARENTRELATIVEPARSING = 0x80018001,
SIGDN_URL = 0x80068000
}
[Flags]
private enum FOS
{
FOS_OVERWRITEPROMPT = 0x2,
FOS_STRICTFILETYPES = 0x4,
FOS_NOCHANGEDIR = 0x8,
FOS_PICKFOLDERS = 0x20,
FOS_FORCEFILESYSTEM = 0x40,
FOS_ALLNONSTORAGEITEMS = 0x80,
FOS_NOVALIDATE = 0x100,
FOS_ALLOWMULTISELECT = 0x200,
FOS_PATHMUSTEXIST = 0x800,
FOS_FILEMUSTEXIST = 0x1000,
FOS_CREATEPROMPT = 0x2000,
FOS_SHAREAWARE = 0x4000,
FOS_NOREADONLYRETURN = 0x8000,
FOS_NOTESTFILECREATE = 0x10000,
FOS_HIDEMRUPLACES = 0x20000,
FOS_HIDEPINNEDPLACES = 0x40000,
FOS_NODEREFERENCELINKS = 0x100000,
FOS_OKBUTTONNEEDSINTERACTION = 0x200000,
FOS_DONTADDTORECENT = 0x2000000,
FOS_FORCESHOWHIDDEN = 0x10000000,
FOS_DEFAULTNOMINIMODE = 0x20000000,
FOS_FORCEPREVIEWPANEON = 0x40000000,
FOS_SUPPORTSTREAMABLEITEMS = unchecked((int)0x80000000)
}
#pragma warning restore CA1712 // Do not prefix enum values with type name
}
result:
The primary goal of a hashmap is to store a data set and provide near constant time lookups on it using a unique key. There are two common styles of hashmap implementation:
Separate chaining is preferable if the hashmap may have a poor hash function, it is not desirable to pre-allocate storage for potentially unused slots, or entries may have variable size. This type of hashmap may continue to function relatively efficiently even when the load factor exceeds 1.0. Obviously, there is extra memory required in each entry to store linked list pointers.
Hashmaps using open addressing have potential performance advantages when the load factor is kept below a certain threshold (generally about 0.7) and a reasonably good hash function is used. This is because they avoid potential cache misses and many small memory allocations associated with a linked list, and perform all operations in a contiguous, pre-allocated array. Iteration through all elements is also cheaper. The catch is hashmaps using open addressing must be reallocated to a larger size and rehashed to maintain an ideal load factor, or they face a significant performance penalty. It is impossible for their load factor to exceed 1.0.
Some key performance metrics to evaluate when creating a hashmap would include:
Here is a flexible hashmap implementation I made. I used open addressing and linear probing for collision resolution.
Try using the html() function.
$('#<%=Label1.ClientID%>').html();
You're also missing the # to make it an ID you're searching for. Without the #, it's looking for a tag type.
On SuSE, there are two different configuration files for PHP: one for Apache, and one for CLI (command line interface). In the /etc/php5/ directory, you will find an "apache2" directory and a "cli" directory. Each has a "php.ini" file. The files are for the same purpose (php configuration), but apply to the two different ways of running PHP. These files, among other things, load the modules PHP uses.
If your OS is similar, then these two files are probably not the same. Your Apache php.ini is probably loading the gearman module, while the cli php.ini isn't. When the module was installed (auto or manual), it probably only updated the Apache php.ini file.
You could simply copy the Apache php.ini file over into the cli directory to make the CLI environment exactly like the Apache environment.
Or, you could find the line that loads the gearman module in the Apache file and copy/paste just it to the CLI file.
In Oracle PL/SQL, if you are running a query that may return multiple rows, you need a cursor to iterate over the results. The simplest way is with a for loop, e.g.:
declare
myname varchar2(20) := 'tom';
begin
for result_cursor in (select * from mytable where first_name = myname) loop
dbms_output.put_line(result_cursor.first_name);
dbms_output.put_line(result_cursor.other_field);
end loop;
end;
If you have a query that returns exactly one row, then you can use the select...into...
syntax, e.g.:
declare
myname varchar2(20);
begin
select first_name into myname
from mytable
where person_id = 123;
end;
There are 2 inputs you might have and you can also convert between them.
example: [{"":{"...
The pd.DataFrame() needs a listOfDictionaries as input.
example: '{"":{"...
If you have jsonStr, you need an extra step to listOfDictionaries first. This is obvious as it is generated like:
jsonStr = json.dumps(listOfDictionaries)
Thus, switch back from jsonStr to listOfDictionaries first:
listOfDictionaries = json.loads(jsonStr)
First you have to get the reference to the View (say Button, TextView, etc.) and set an OnClickListener to the reference using setOnClickListener() method
// get reference to button
val btn_click_me = findViewById(R.id.btn_click_me) as Button
// set on-click listener
btn_click_me.setOnClickListener {
Toast.makeText(this@MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show()
}
Refer Kotlin SetOnClickListener Example for complete Kotlin Android Example where a button is present in an activity and OnclickListener is applied to the button. When you click on the button, the code inside SetOnClickListener block is executed.
Update
Now you can reference the button directly with its id by including the following import statement in Class file. Documentation.
import kotlinx.android.synthetic.main.activity_main.*
and then for the button
btn_click_me.setOnClickListener {
// statements to run when button is clicked
}
Refer Android Studio Tutorial.
Transaction can be defined as a collection of task that are considered as minimum processing unit. Each minimum processing unit can not be divided further.
The main operation of a transaction are read and write.
All transaction must contain four properties that commonly known as ACID properties for the purpose of ensuring accuracy , completeness and data integrity.
From Python 3.0 changelog;
The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.
From the Python 3 email documentation it can be seen that io.StringIO
should be used instead:
from io import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()
Reference: https://docs.python.org/3/library/io.html
I had a special case of this: I had a file with --assume-unchanged on it. It was hard to locate, as the git status
command was not showing any changes
You can include a legend template in the chart options:
//legendTemplate takes a template as a string, you can populate the template with values from your dataset
var options = {
legendTemplate : '<ul>'
+'<% for (var i=0; i<datasets.length; i++) { %>'
+'<li>'
+'<span style=\"background-color:<%=datasets[i].lineColor%>\"></span>'
+'<% if (datasets[i].label) { %><%= datasets[i].label %><% } %>'
+'</li>'
+'<% } %>'
+'</ul>'
}
//don't forget to pass options in when creating new Chart
var lineChart = new Chart(element).Line(data, options);
//then you just need to generate the legend
var legend = lineChart.generateLegend();
//and append it to your page somewhere
$('#chart').append(legend);
You'll also need to add some basic css to get it looking ok.
There are two versions: 1 and 4. EFv4 is part of .net 4.0, and EFv1 is part of .net 3.5 SP1.
Yes, the config setting above points to EFv4 / .net 4.0.
EDIT
If you open the references folder and locate system.data.entity
, click the item, then check the runtime version number in the Properties explorer, you will see the sub version as well. Mine for instance shows runtime version v4.0.30319 with the Version property showing 4.0.0.0. The EntityFramework.dll
can be viewed in this fashion also. Only the Version will be 4.1.0.0 and the Runtime version will be v4.0.30319 which specifies it is a .NET 4 component. Alternatively, you can open the file location as listed in the Path property and right-click the component in question, choose properties, then choose the details tab and view the product version.
If you're using V4.1, and according to their docs, don't assign .table-responsive directly to the table. The table should be .table and if you want it to be horizontally scrollable (responsive) add it inside a .table-responsive container (a <div>
, for instance).
Responsive tables allow tables to be scrolled horizontally with ease. Make any table responsive across all viewports by wrapping a .table with .table-responsive.
<div class="table-responsive">
<table class="table">
...
</table>
</div>
doing that, no extra css is needed.
In the OP's code, .table-responsive can be used alongside with the .col-md-12 on the outside .
It's easier and cleaner to do it with CSS.
HTML:
<div ng-repeat="file in files" class="file">
{{ file.name }}
</div>
CSS:
.file:last-of-type {
color: #800;
}
The :last-of-type
selector is currently supported by 98% of browsers
"...by a class and a div."
I assume when you say "div" you mean "id"? Try this:
$('#test2.test1').prop('checked', true);
No need to muck about with your [attributename=value]
style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".
Or more generally to select an input where you want to specify a multiple attribute selector:
$('input:radio[class=test1][id=test2]').prop('checked', true);
That is, list each attribute with its own square brackets.
Note that unless you have a pretty old version of jQuery you should use .prop()
rather than .attr()
for this purpose.
One of the best options is to go for MongoDB(NOSql dB) that supports scalability.Stores large amounts of data nothing but bigdata in the form of documents unlike rows and tables in sql.This is fasters that follows sharding of the data.Uses replicasets to ensure data guarantee that maintains multiple servers having primary db server as the base. Language independent. Flexible to use
As mentioned in several other answers here, this 'accepted' answer is outdated and is no longer correct. VS Code now has the concept of a 'workspace' which lets you add several 'root' folders to VS Code in the same window.
For instance, when working on a project in one folder that utilizes shared code held in a different folder, you can now open both the project folder and the shared folder in the same window.
To do this you use the Add folder to Workspace...
command. VS Code then saves this configuration in a new file with a .code-workspace
extension. If you double-click that file, VS Code will re-open with both folders present.
As described in The Basics of Visual Studio Code article:
"VSCode is file and folder based - you can get started immediately by opening a file or folder in VSCode."
This means the concept of solution and project files, like the .sln and .csproj, have no real function in VSCode other than that it uses these only to target and identify which language to support for Intellisense and such.
Simply put, the folder you open is the root you work with. But of course there is nothing from stopping you to open multiple windows.
As for the request features options, navigate to Help > Request Features which will redirect you to the UserVoice page of VSCode.
var startDt=document.getElementById("startDateId").value;
var endDt=document.getElementById("endDateId").value;
if( (new Date(startDt).getTime() > new Date(endDt).getTime()))
{
----------------------------------
}
(This is pointed out in a comment by Zan Lynx, but I think it deserves an aswer - given that the accepted answer doesn't mention it).
The essential difference between puts(mystr);
and printf(mystr);
is that in the latter the argument is interpreted as a formatting string. The result will be often the same (except for the added newline) if the string doesn't contain any control characters (%
) but if you cannot rely on that (if mystr
is a variable instead of a literal) you should not use it.
So, it's generally dangerous -and conceptually wrong- to pass a dynamic string as single argument of printf
:
char * myMessage;
// ... myMessage gets assigned at runtime, unpredictable content
printf(myMessage); // <--- WRONG! (what if myMessage contains a '%' char?)
puts(myMessage); // ok
printf("%s\n",myMessage); // ok, equivalent to the previous, perhaps less efficient
The same applies to fputs
vs fprintf
(but fputs
doesn't add the newline).
schtasks /change /disable /tn "Name Of Task" /s REMOTEMACHINENAME /u mydomain\administrator /p adminpassword
A jar
file is a zip file with some additional files containing metadata. (Despite the .jar extension, it is in zip format, and any utilities that deal with .zip files are also able to deal with .jar files.)
http://docs.oracle.com/javase/8/docs/technotes/guides/jar/index.html
Jar files can contain any kind of files, but they usually contain class files and supporting configuration files (properties), graphics and other data files needed by the application.
Class files contain compiled Java code, which is executable by the Java Virtual Machine.
If you have MySQL version >= 5.7, then you can try this:
SELECT JSON_EXTRACT(name, "$.id") AS name
FROM table
WHERE JSON_EXTRACT(name, "$.id") > 3
Output:
+-------------------------------+
| name |
+-------------------------------+
| {"id": "4", "name": "Betty"} |
+-------------------------------+
Please check MySQL reference manual for more details:
https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html
string replace() function perfectly solves this problem:
string.replace(s, old, new[, maxreplace])
Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.
>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'
The error is pretty clear. The file hello.py
is not an executable file. You need to specify the executable:
subprocess.call(['python.exe', 'hello.py', 'htmlfilename.htm'])
You'll need python.exe
to be visible on the search path, or you could pass the full path to the executable file that is running the calling script:
import sys
subprocess.call([sys.executable, 'hello.py', 'htmlfilename.htm'])
It's even easier to use parent > child selector relationship so the inner div do not need to have their css classes to be defined explicitly:
.display-table {_x000D_
display: table; _x000D_
}_x000D_
.display-table > div { _x000D_
display: table-row; _x000D_
}_x000D_
.display-table > div > div { _x000D_
display: table-cell;_x000D_
padding: 5px;_x000D_
}
_x000D_
<div class="display-table">_x000D_
<div>_x000D_
<div>0, 0</div>_x000D_
<div>0, 1</div>_x000D_
</div>_x000D_
<div>_x000D_
<div>1, 0</div>_x000D_
<div>1, 1</div>_x000D_
</div>_x000D_
</div>
_x000D_
Instead of casting to float, you can add 0.0 to the sum:
def avg(l):
return sum(l, 0.0) / len(l)
This is simply not possible. There is no physical connection between you and the server (except in the extremely rare case where you are connecting between two compuers with a loopback cable).
When the connection is closed gracefully, the other side is notified. But if the connection is disconnected some other way (say the users connection is dropped) then the server won't know until it times out (or tries to write to the connection and the ack times out). That's just the way TCP works and you have to live with it.
Therefore, "instantly" is unrealistic. The best you can do is within the timeout period, which depends on the platform the code is running on.
EDIT: If you are only looking for graceful connections, then why not just send a "DISCONNECT" command to the server from your client?
If you don't mind getting a new data frame object returned as opposed to updating the original Pandas .assign() will avoid SettingWithCopyWarning
. Your example:
df = df.assign(B=df1['E'])
Obviously , packet length * propagation delay = trasmission delay is wrong.
Let us assume that you have a packet which has 4 bits 1010.You have to send it from A to B.
For this scenario,Transmission delay is the time taken by the sender to place the packet on the link(Transmission medium).Because the bits(1010) has to be converted in to signals.So it takes some time.Note that here only the packet is placed.It is not moving to receiver.
Propagation delay is the time taken by a bit(Mostly MSB ,Here 1) to reach from sender(A) to receiver(B).
There are a few ways to handle that; Vanilla JavaScript can do it quite nicely:
function code(e) {
e = e || window.event;
return(e.keyCode || e.which);
}
window.onload = function(){
document.onkeypress = function(e){
var key = code(e);
// do something with key
};
};
Or a more structured way of handling it:
(function(d){
var modern = (d.addEventListener), event = function(obj, evt, fn){
if(modern) {
obj.addEventListener(evt, fn, false);
} else {
obj.attachEvent("on" + evt, fn);
}
}, code = function(e){
e = e || window.event;
return(e.keyCode || e.which);
}, init = function(){
event(d, "keypress", function(e){
var key = code(e);
// do stuff with key here
});
};
if(modern) {
d.addEventListener("DOMContentLoaded", init, false);
} else {
d.attachEvent("onreadystatechange", function(){
if(d.readyState === "complete") {
init();
}
});
}
})(document);
I know this is old but in case it is helpful to others:
If you need to run a script and want the terminal to pop up so you can see the results you can do like Abyss Knight said and change the extension to .command. If you double click on it it will open a terminal window and run.
I however needed this to run from automator or appleScript. So to get this to open a new terminal the command I ran from "run shell script" was "open myShellScript.command" and it opened in a new terminal.
To pull from the default branch, new repositories should use the command:
git pull origin main
Github changed naming convention of default branch from master to main in 2020. https://github.com/github/renaming
Referencing the connection string should be done as such:
MySQLHelper.ExecuteNonQuery(
ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString,
CommandType.Text,
sqlQuery,
sqlParams);
ConfigurationManager.AppSettings["ConnectionString"]
would be looking in the AppSettings
for something named ConnectionString
, which it would not find. This is why your error message indicated the "ConnectionString" property has not been initialized
, because it is looking for an initialized property of AppSettings
named ConnectionString
.
ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString
instructs to look for the connection string named "MyDB".
Here is someone talking about using web.config connection strings
you can use
@Html.Raw(str)
See MSDN for more
Returns markup that is not HTML encoded.
This method wraps HTML markup using the IHtmlString class, which renders unencoded HTML.
I've colour coded this figure to ease the process.
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
You can have full control over the figure using these commands, to complete the answer I've add also the control over the splines:
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
# X AXIS -BORDER
ax.spines['bottom'].set_visible(False)
# BLUE
ax.set_xticklabels([])
# RED
ax.set_xticks([])
# RED AND BLUE TOGETHER
ax.axes.get_xaxis().set_visible(False)
# Y AXIS -BORDER
ax.spines['left'].set_visible(False)
# YELLOW
ax.set_yticklabels([])
# GREEN
ax.set_yticks([])
# YELLOW AND GREEN TOGHETHER
ax.axes.get_yaxis().set_visible(False)
Do you want people to focus on the content, and demonstrate that you're a person of taste and good sense? Stay with Courier. Don't innovate just because you can (otherwise, why not craft exquisite animations for every slide transition, with dancing letters...?).
Courier has several advantages:
If you want to dump point 4, at least choose an alternative that preserves points 1-3. Never allow form to trump function.
SIGKILL
use to kill the process. SIGKILL
can not be ignored or handled. In Linux, Ways to give SIGKILL
.
kill -9 <process_pid>
kill -SIGKILL <process_pid>
killall -SIGKILL <process_name>
killall -9 <process_name>
Hope this would be useful to you. ^o^
df1 = pd.DataFrame({'date': ['0207', '0207'], 'col1': [1, 2]})
df2 = pd.DataFrame({'date': ['0207', '0207', '0208', '0208'], 'col1': [1, 2, 3, 4]})
print(f"df1(Before):\n{df1}\ndf2:\n{df2}")
"""
df1(Before):
date col1
0 0207 1
1 0207 2
df2:
date col1
0 0207 1
1 0207 2
2 0208 3
3 0208 4
"""
old_set = set(df1.index.values)
new_set = set(df2.index.values)
new_data_index = new_set - old_set
new_data_list = []
for idx in new_data_index:
new_data_list.append(df2.loc[idx])
if len(new_data_list) > 0:
df1 = df1.append(new_data_list)
print(f"df1(After):\n{df1}")
"""
df1(After):
date col1
0 0207 1
1 0207 2
2 0208 3
3 0208 4
"""
For the next person Googling this topic, I've written a small NPM package to make it simple to generate Google Calendar URLs. It includes TypeScript type definitions, for those who need that. Hope it helps!
If you don't want to or can't use instanceof
, then compare with equals
:
if(obj.getClass().equals(MyObject.class)) System.out.println("true");
BTW - it's strange because the two Class
instances in your statement really should be the same, at least in your example code. They may be different if:
Use the same function (cor
) on a data frame, e.g.:
> cor(VADeaths)
Rural Male Rural Female Urban Male Urban Female
Rural Male 1.0000000 0.9979869 0.9841907 0.9934646
Rural Female 0.9979869 1.0000000 0.9739053 0.9867310
Urban Male 0.9841907 0.9739053 1.0000000 0.9918262
Urban Female 0.9934646 0.9867310 0.9918262 1.0000000
Or, on a data frame also holding discrete variables, (also sometimes referred to as factors), try something like the following:
> cor(mtcars[,unlist(lapply(mtcars, is.numeric))])
mpg cyl disp hp drat wt qsec vs am gear carb
mpg 1.0000000 -0.8521620 -0.8475514 -0.7761684 0.68117191 -0.8676594 0.41868403 0.6640389 0.59983243 0.4802848 -0.55092507
cyl -0.8521620 1.0000000 0.9020329 0.8324475 -0.69993811 0.7824958 -0.59124207 -0.8108118 -0.52260705 -0.4926866 0.52698829
disp -0.8475514 0.9020329 1.0000000 0.7909486 -0.71021393 0.8879799 -0.43369788 -0.7104159 -0.59122704 -0.5555692 0.39497686
hp -0.7761684 0.8324475 0.7909486 1.0000000 -0.44875912 0.6587479 -0.70822339 -0.7230967 -0.24320426 -0.1257043 0.74981247
drat 0.6811719 -0.6999381 -0.7102139 -0.4487591 1.00000000 -0.7124406 0.09120476 0.4402785 0.71271113 0.6996101 -0.09078980
wt -0.8676594 0.7824958 0.8879799 0.6587479 -0.71244065 1.0000000 -0.17471588 -0.5549157 -0.69249526 -0.5832870 0.42760594
qsec 0.4186840 -0.5912421 -0.4336979 -0.7082234 0.09120476 -0.1747159 1.00000000 0.7445354 -0.22986086 -0.2126822 -0.65624923
vs 0.6640389 -0.8108118 -0.7104159 -0.7230967 0.44027846 -0.5549157 0.74453544 1.0000000 0.16834512 0.2060233 -0.56960714
am 0.5998324 -0.5226070 -0.5912270 -0.2432043 0.71271113 -0.6924953 -0.22986086 0.1683451 1.00000000 0.7940588 0.05753435
gear 0.4802848 -0.4926866 -0.5555692 -0.1257043 0.69961013 -0.5832870 -0.21268223 0.2060233 0.79405876 1.0000000 0.27407284
carb -0.5509251 0.5269883 0.3949769 0.7498125 -0.09078980 0.4276059 -0.65624923 -0.5696071 0.05753435 0.2740728 1.00000000
You can store images in MySQL as blobs. However, this is problematic for a couple of reasons:
Instead, consider updating your table to add an image_path field. For example:
ALTER TABLE `your_table`
ADD COLUMN `image_path` varchar(1024)
Then store your images on disk, and update the table with the image path. When you need to use the images, retrieve them from disk using the path specified.
An advantageous side-effect of this approach is that the images do not necessarily be stored on disk; you could just as easily store a URL instead of an image path, and retrieve images from any internet-connected location.
Updating my Java SDK to the latest version 1.7.0_79
and updating the SDK Location
under Project Structure
solved the problem for me.
As described here http://developer.android.com/reference/java/util/regex/Pattern.html
Patterns are compiled regular expressions. In many cases, convenience methods such as
String.matches
,String.replaceAll
andString.split
will be preferable, but if you need to do a lot of work with the same regular expression, it may be more efficient to compile it once and reuse it. The Pattern class and its companion, Matcher, also offer more functionality than the small amount exposed by String.
public class RegularExpressionTest {
public static void main(String[] args) {
System.out.println("String is = "+getOnlyStrings("!&(*^*(^(+one(&(^()(*)(*&^%$#@!#$%^&*()("));
System.out.println("Number is = "+getOnlyDigits("&(*^*(^(+91-&*9hi-639-0097(&(^("));
}
public static String getOnlyDigits(String s) {
Pattern pattern = Pattern.compile("[^0-9]");
Matcher matcher = pattern.matcher(s);
String number = matcher.replaceAll("");
return number;
}
public static String getOnlyStrings(String s) {
Pattern pattern = Pattern.compile("[^a-z A-Z]");
Matcher matcher = pattern.matcher(s);
String number = matcher.replaceAll("");
return number;
}
}
Result
String is = one
Number is = 9196390097
^[+-]?(([1-9][0-9]*)?[0-9](\.[0-9]*)?|\.[0-9]+)$
should reflect what people usually think of as a well formed decimal number.
The digits before the decimal point can be either a single digit, in which case it can be from 0 to 9, or more than one digits, in which case it cannot start with a 0.
If there are any digits present before the decimal sign, then the decimal and the digits following it are optional. Otherwise, a decimal has to be present followed by at least one digit. Note that multiple trailing 0's are allowed after the decimal point.
grep -E '^[+-]?(([1-9][0-9]*)?[0-9](\.[0-9]*)?|\.[0-9]+)$'
correctly matches the following:
9
0
10
10.
0.
0.0
0.100
0.10
0.01
10.0
10.10
.0
.1
.00
.100
.001
as well as their signed equivalents, whereas it rejects the following:
.
00
01
00.0
01.3
and their signed equivalents, as well as the empty string.
To stop a for
loop early in JavaScript, you use break
:
var remSize = [],
szString,
remData,
remIndex,
i;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = -1; // Set a default if we don't find it
for (i = 0; i < remSize.length; i++) {
// I'm looking for the index i, when the condition is true
if (remSize[i].size === remData.size) {
remIndex = i;
break; // <=== breaks out of the loop early
}
}
If you're in an ES2015 (aka ES6) environment, for this specific use case, you can use Array#findIndex
(to find the entry's index) or Array#find
(to find the entry itself), both of which can be shimmed/polyfilled:
var remSize = [],
szString,
remData,
remIndex;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = remSize.findIndex(function(entry) {
return entry.size === remData.size;
});
Array#find
:
var remSize = [],
szString,
remData,
remEntry;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remEntry = remSize.find(function(entry) {
return entry.size === remData.size;
});
Array#findIndex
stops the first time the callback returns a truthy value, returning the index for that call to the callback; it returns -1
if the callback never returns a truthy value. Array#find
also stops when it finds what you're looking for, but it returns the entry, not its index (or undefined
if the callback never returns a truthy value).
If you're using an ES5-compatible environment (or an ES5 shim), you can use the new some
function on arrays, which calls a callback until the callback returns a truthy value:
var remSize = [],
szString,
remData,
remIndex;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = -1; // <== Set a default if we don't find it
remSize.some(function(entry, index) {
if (entry.size === remData.size) {
remIndex = index;
return true; // <== Equivalent of break for `Array#some`
}
});
If you're using jQuery, you can use jQuery.each
to loop through an array; that would look like this:
var remSize = [],
szString,
remData,
remIndex;
/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */
remIndex = -1; // <== Set a default if we don't find it
jQuery.each(remSize, function(index, entry) {
if (entry.size === remData.size) {
remIndex = index;
return false; // <== Equivalent of break for jQuery.each
}
});
Add empty tr
before your table tr tags.
As stated by Taylor L, you can't just "stop" a thread (by calling a simple method) due to the fact that it could leave your system in an unstable state as the external calling thread may not know what is going on inside your thread.
With this said, the best way to "stop" a thread is to have the thread keep an eye on itself and to have it know and understand when it should stop.
This will get the index of the selected option on change:
$('select').change(function(){_x000D_
console.log($('option:selected',this).index()); _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select name="CCards">_x000D_
<option value="0">Select Saved Payment Method:</option>_x000D_
<option value="1846">test xxxx1234</option>_x000D_
<option value="1962">test2 xxxx3456</option>_x000D_
</select>
_x000D_
Try also to use the cksum command:
chk1=`cksum <file1> | awk -F" " '{print $1}'`
chk2=`cksum <file2> | awk -F" " '{print $1}'`
if [ $chk1 -eq $chk2 ]
then
echo "File is identical"
else
echo "File is not identical"
fi
The cksum command will output the byte count of a file. See 'man cksum'.
Duplicated id
for pairs name
and city
:
select s.id, t.*
from [stuff] s
join (
select name, city, count(*) as qty
from [stuff]
group by name, city
having count(*) > 1
) t on s.name = t.name and s.city = t.city
Be careful, -
has a special meaning with regexp. In a []
, you can put it without problem if it is placed at the end. In your case, ,-:
is taken as from ,
to :
.
Try this:
-webkit-column-break-inside: avoid;
page-break-inside: avoid;
break-inside: avoid;
-webkit-column-break-inside: avoid-column;
page-break-inside: avoid-column;
break-inside: avoid-column;
...worked for me, might work for you.
window
/tab
.https://developer.mozilla.org/en-US/docs/Web/API/Window/open#Syntax
_self
<a
href="url"
target="_self">
open
</a>
const autoOpenAlink = (url = ``) => {
window.open(url, "open testing page in the same tab page");
}
_blank
vue demo
<div style="margin: 5px;">
<a
:href="url"
@click="autoOpenAlink"
target="_blank"
>
{{url}}
</a>
</div>
vue
autoOpenAlink(e) {
e.preventDefault();
let url = this.url;
window.open(url, "iframe testing page");
},
As a quick example (using a slightly cleaner method than the potentially duplicate question):
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.spines['bottom'].set_color('red')
ax.spines['top'].set_color('red')
ax.xaxis.label.set_color('red')
ax.tick_params(axis='x', colors='red')
plt.show()
[t.set_color('red') for t in ax.xaxis.get_ticklines()]
[t.set_color('red') for t in ax.xaxis.get_ticklabels()]
OK, in JavaScript we don't have a range()
function like PHP, so we need to create the function which is quite easy thing, I write couple of one-line functions for you and separate them for Numbers and Alphabets as below:
for Numbers:
function numberRange (start, end) {
return new Array(end - start).fill().map((d, i) => i + start);
}
and call it like:
numberRange(5, 10); //[5, 6, 7, 8, 9]
for Alphabets:
function alphabetRange (start, end) {
return new Array(end.charCodeAt(0) - start.charCodeAt(0)).fill().map((d, i) => String.fromCharCode(i + start.charCodeAt(0)));
}
and call it like:
alphabetRange('c', 'h'); //["c", "d", "e", "f", "g"]
Here i will demonstrate you that how to make your decimal number short. Here i am going to make it short upto 4 value after decimal.
double value = 12.3457652133
value =Double.parseDouble(new DecimalFormat("##.####").format(value));
Here is a one-liner for you.
Replace $jQueryObject
with your jQuery object. i.e $('div')
.
Object.values($jQueryObject.get(0).attributes).map(attr => console.log(`${attr.name + ' : ' + attr.value}`));
Replace $domElement
with your HTML DOM selector. i.e document.getElementById('demo')
.
Object.values($domElement.attributes).map(attr => console.log(`${attr.name + ' : ' + attr.value}`));
Cheers!!
Similar to Ghommey's answer, but this also supports old versions of IE and Firefox.
window.onbeforeunload = function (e) {
var message = "Your confirmation message goes here.",
e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
};
.joins
will just joins the tables and brings selected fields in return. if you call associations on joins query result, it will fire database queries again
:includes
will eager load the included associations and add them in memory. :includes
loads all the included tables attributes. If you call associations on include query result, it will not fire any queries
AssertionError is an Unchecked Exception which rises explicitly by programmer or by API Developer to indicate that assert statement fails.
assert(x>10);
Output:
AssertionError
If x is not greater than 10 then you will get runtime exception saying AssertionError.
There is no Boolean
class in Ruby, the only way to check is to do what you're doing (comparing the object against true
and false
or the class of the object against TrueClass
and FalseClass
). Can't think of why you would need this functionality though, can you explain? :)
If you really need this functionality however, you can hack it in:
module Boolean; end
class TrueClass; include Boolean; end
class FalseClass; include Boolean; end
true.is_a?(Boolean) #=> true
false.is_a?(Boolean) #=> true
I encountered the No module named psycopg2.extensions
error when trying to run pip2 install psycopg2
on a Mac running Mavericks (10.9). I don't think my stack trace included a message about gcc, and it also included a hint:
Error: pg_config executable not found.
Please add the directory containing pg_config to the PATH
or specify the full executable path with the option:
python setup.py build_ext --pg-config /path/to/pg_config build ...
or with the pg_config option in 'setup.cfg'.
I looked for the pg_config
file in my Postgres install and added the folder containing it to my path: /Applications/Postgres.app/Contents/Versions/9.4/bin
. Your path may be different, especially if you have a different version of Postgres installed - I would just poke around until you find the bin/
folder. After doing this, the installation worked.
This may not be the prettiest, but if you don't want to use the MessageBoxManager, (which is awesome):
public static DialogResult DialogBox(string title, string promptText, ref string value, string button1 = "OK", string button2 = "Cancel", string button3 = null)
{
Form form = new Form();
Label label = new Label();
TextBox textBox = new TextBox();
Button button_1 = new Button();
Button button_2 = new Button();
Button button_3 = new Button();
int buttonStartPos = 228; //Standard two button position
if (button3 != null)
buttonStartPos = 228 - 81;
else
{
button_3.Visible = false;
button_3.Enabled = false;
}
form.Text = title;
// Label
label.Text = promptText;
label.SetBounds(9, 20, 372, 13);
label.Font = new Font("Microsoft Tai Le", 10, FontStyle.Regular);
// TextBox
if (value == null)
{
}
else
{
textBox.Text = value;
textBox.SetBounds(12, 36, 372, 20);
textBox.Anchor = textBox.Anchor | AnchorStyles.Right;
}
button_1.Text = button1;
button_2.Text = button2;
button_3.Text = button3 ?? string.Empty;
button_1.DialogResult = DialogResult.OK;
button_2.DialogResult = DialogResult.Cancel;
button_3.DialogResult = DialogResult.Yes;
button_1.SetBounds(buttonStartPos, 72, 75, 23);
button_2.SetBounds(buttonStartPos + 81, 72, 75, 23);
button_3.SetBounds(buttonStartPos + (2 * 81), 72, 75, 23);
label.AutoSize = true;
button_1.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
button_2.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
button_3.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
form.ClientSize = new Size(396, 107);
form.Controls.AddRange(new Control[] { label, button_1, button_2 });
if (button3 != null)
form.Controls.Add(button_3);
if (value != null)
form.Controls.Add(textBox);
form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height);
form.FormBorderStyle = FormBorderStyle.FixedDialog;
form.StartPosition = FormStartPosition.CenterScreen;
form.MinimizeBox = false;
form.MaximizeBox = false;
form.AcceptButton = button_1;
form.CancelButton = button_2;
DialogResult dialogResult = form.ShowDialog();
value = textBox.Text;
return dialogResult;
}
You can use a FileReader
object to read text file here is example code:
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
<script>
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
</script>
Here is the codepen demo
If you have a fixed file to read every time your application load then you can use this code :
<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
fileDisplayArea.innerText = allText
}
}
}
rawFile.send(null);
}
readTextFile("file:///C:/your/path/to/file.txt");
</script>
Check jQuery.ScrollTo, I think that's the behavior that you want, check the demo.
If you want to disable a single transition property, you can do:
transition: color 0s;
(since a zero second transition is the same as no transition.)
This might be more desirable, that is use float instead
SELECT fullName, CAST(totalBal as float) totalBal FROM client_info ORDER BY totalBal DESC
One more alternative options
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 1,
center: new google.maps.LatLng(35.137879, -82.836914),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(47.651968, 9.478485),
draggable: true
});
google.maps.event.addListener(myMarker, 'dragend', function (evt) {
document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
});
google.maps.event.addListener(myMarker, 'dragstart', function (evt) {
document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
});
map.setCenter(myMarker.position);
myMarker.setMap(map);
and html file
<body>
<section>
<div id='map_canvas'></div>
<div id="current">Nothing yet...</div>
</section>
</body>
If you need to programatically check for aprox. size of objects you can also check this library http://code.stephenmorley.org/javascript/finding-the-memory-usage-of-objects/ that I have been able to use for objects size.
Otherwise I suggest to use the Chrome/Firefox Heap Profiler.
You can use ISNULL
:
ISNULL(field, VALUEINCASEOFNULL)
--This is for oracle
SELECT DISTINCT City FROM Station WHERE MOD(Id,2) = 0 ORDER BY City;
One should check if QtyToRepair
is updated at first.
ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified]
ON [dbo].[SCHEDULE]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
IF UPDATE (QtyToRepair)
BEGIN
UPDATE SCHEDULE
SET modified = GETDATE()
, ModifiedUser = SUSER_NAME()
, ModifiedHost = HOST_NAME()
FROM SCHEDULE S INNER JOIN Inserted I
ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber
WHERE S.QtyToRepair <> I.QtyToRepair
END
END
I faced the error "TypeError: 'NoneType' object is not callable " but for a different issue. With the above clues, i was able to debug and got it right! The issue that i faced was : I had the custome Library written and my file wasnt recognizing it although i had mentioned it
example:
Library ../../../libraries/customlibraries/ExtendedWaitKeywords.py
the keywords from my custom library were recognized and that error was resolved only after specifying the complete path, as it was not getting the callable function.
SimpleDateFormat("MM-dd-yyyy");
instead of
SimpleDateFormat("mm-dd-yyyy");
because MM points Month
, mm points minutes
SimpleDateFormat sm = new SimpleDateFormat("MM-dd-yyyy");
String strDate = sm.format(myDate);
I really liked this answer, with ngBind, your default text can just live in the element body, and then if the ngBind evaluates to something non-null/undefined, your content is replaced automatically, and everythings happy
angularjs setting default values to display before evaluation
for (int i = 0; i < 5; i++){
int asciiVal = rand()%26 + 97;
char asciiChar = asciiVal;
cout << asciiChar << " and ";
}
Radio buttons would only need to be read-only if there are other options. If you don't have any other options, a checked radio button cannot be unchecked. If you have other options, you can prevent the user from changing the value merely by disabling the other options:
<input type="radio" name="foo" value="Y" checked>
<input type="radio" name="foo" value="N" disabled>
Fiddle: http://jsfiddle.net/qqVGu/
I like:
df['new'] = pd.Series(dtype='your_required_dtype')
If you have an empty dataframe, this solution makes sure that no new row containing only NaN
is added.
Specifying dtype
is not strictly necessary, however newer Pandas versions produce a DeprecationWarning
if not specified.
If you're using the command-line tools, running git --version
should give you the version number.
Just to help those in a similar situation to myself...
This can be caused when a dependent library has accidentally bundled an old version of slf4j. In my case, it was tika-0.8. See https://issues.apache.org/jira/browse/TIKA-556
The workaround is exclude the component and then manually depends on the correct, or patched version.
EG.
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-parsers</artifactId>
<version>0.8</version>
<exclusions>
<exclusion>
<!-- NOTE: Version 4.2 has bundled slf4j -->
<groupId>edu.ucar</groupId>
<artifactId>netcdf</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<!-- Patched version 4.2-min does not bundle slf4j -->
<groupId>edu.ucar</groupId>
<artifactId>netcdf</artifactId>
<version>4.2-min</version>
</dependency>
In Scala it is very comfortable with https://github.com/lloydmeta/enumeratum
Project is really good with examples and documentation
Just this example from their docs should makes you interested in
import enumeratum._
sealed trait Greeting extends EnumEntry
object Greeting extends Enum[Greeting] {
/*
`findValues` is a protected method that invokes a macro to find all `Greeting` object declarations inside an `Enum`
You use it to implement the `val values` member
*/
val values = findValues
case object Hello extends Greeting
case object GoodBye extends Greeting
case object Hi extends Greeting
case object Bye extends Greeting
}
// Object Greeting has a `withName(name: String)` method
Greeting.withName("Hello")
// => res0: Greeting = Hello
Greeting.withName("Haro")
// => java.lang.IllegalArgumentException: Haro is not a member of Enum (Hello, GoodBye, Hi, Bye)
// A safer alternative would be to use `withNameOption(name: String)` method which returns an Option[Greeting]
Greeting.withNameOption("Hello")
// => res1: Option[Greeting] = Some(Hello)
Greeting.withNameOption("Haro")
// => res2: Option[Greeting] = None
// It is also possible to use strings case insensitively
Greeting.withNameInsensitive("HeLLo")
// => res3: Greeting = Hello
Greeting.withNameInsensitiveOption("HeLLo")
// => res4: Option[Greeting] = Some(Hello)
// Uppercase-only strings may also be used
Greeting.withNameUppercaseOnly("HELLO")
// => res5: Greeting = Hello
Greeting.withNameUppercaseOnlyOption("HeLLo")
// => res6: Option[Greeting] = None
// Similarly, lowercase-only strings may also be used
Greeting.withNameLowercaseOnly("hello")
// => res7: Greeting = Hello
Greeting.withNameLowercaseOnlyOption("hello")
// => res8: Option[Greeting] = Some(Hello)
In my case, i got this error trying to get an object on an S3 bucket folder. But in that folder my object was not here (i put the wrong folder), so S3 send this message. Hope it could help you too.
var myEle = document.getElementById("myElement");
if(myEle){
var myEleValue= myEle.value;
}
the return of getElementById is null if an element is not actually present inside the dom, so your if statement will fail, because null is considered a false value
#function call
read_names(names.txt)
#function def
def read_names(filename):
with open(filename, 'r') as fileopen:
name_list = [line.strip() for line in fileopen]
print (name_list)
One caveat: in .NET the linefeed is "\r\n". So if you're loading your text from a file, you might have to use that instead of just "\n"
edit> as samuel pointed out in the comments, "\r\n" is not .NET specific, but is windows specific.
In my case, I had a repo with:
.json
.lock
In the meantime, A,B,C had newer versions with respect when the lock was generated.
For some reason, I deleted the "vendors" and wanted to do a composer install
and failed with the message:
Warning: The lock file is not up to date with the latest changes in composer.json.
You may be getting outdated dependencies. Run update to update them.
Your requirements could not be resolved to an installable set of packages.
I tried to run the solution from Seldaek issuing a composer update vendorD/libraryD
but composer insisted to update more things, so .lock
had too changes seen my my git tool.
The solution I used was:
vendors
dir.VendorD/LibraryD
from the .json
.composer install
..json
and checkout it again from the repo (equivalent to re-adding the file, but avoiding potential whitespace changes).composer update vendorD/libraryD
It did install the library, but in addition, git
diff showed me that in the .lock
only the new things were added without editing the other ones.
(Thnx Seldaek for the pointer ;) )
Add:
allow_url_fopen=1
in your php.ini
file. If you are using shared hosting, create one first.
If you need something quick, datetime_object.date()
gives you a date of a datetime object.
Ironically the Scala break in scala.util.control.Breaks
is an exception:
def break(): Nothing = { throw breakException }
The best advice is: DO NOT use break, continue and goto! IMO they are the same, bad practice and an evil source of all kind of problems (and hot discussions) and finally "considered be harmful". Code block structured, also in this example breaks are superfluous. Our Edsger W. Dijkstra† wrote:
The quality of programmers is a decreasing function of the density of go to statements in the programs they produce.
Be really careful with the "Base64().encode()"approach, my team and I got 400 Apache bad request issues because it adds a \r\n at the end of the string generated.
We found it sniffing packets thanks to Wireshark.
Here is our solution :
import org.apache.commons.codec.binary.Base64;
HttpGet getRequest = new HttpGet(endpoint);
getRequest.addHeader("Authorization", "Basic " + getBasicAuthenticationEncoding());
private String getBasicAuthenticationEncoding() {
String userPassword = username + ":" + password;
return new String(Base64.encodeBase64(userPassword.getBytes()));
}
Hope it helps!
For my condition the cause was taking int
parameter for TextView
. Let me show an example
int i = 5;
myTextView.setText(i);
gets the error info above.
This can be fixed by converting int
to String
like this
myTextView.setText(String.valueOf(i));
As you write int
, it expects a resource not the text that you are writing. So be careful on setting an int
as a String
in Android.
With the new CSS3 features, you could rotate the page the opposite orientation that they rotated. Sorry, no IE7- support. :(.
var rotate = 0 - window.orientation;
setAttribute("transform:rotate("+rotate+"deg);-ms-transform:rotate("+rotate+"deg);-webkit-transform:rotate("+rotate+"deg)", "style");
I am using Tensorflow version 2.3.1 and none of the solutions above have been fully effective.
Until, I find this package.
Install like this:
with Anaconda,
python -m pip install silence-tensorflow
with IDEs,
pip install silence-tensorflow
And add to the first line of code:
from silence_tensorflow import silence_tensorflow
silence_tensorflow()
That's It!
I would think to stick with JSP, servlets and JSTL After more than 12 years dealing with web frameworks in several companies I worked with, I always find my self go back to good old JSP. Yes there are some things you need to write yourself that some frameworks do automatically. But if you approach it correctly, and build some basic utils on top of your servlets, it gives the best flexibility and you can do what ever you want easily. I did not find real advantages to write in any of the frameworks. And I keep looking.
Looking at all the answers above also means that there is no real one framework that is good and rules.
And I would love a pony, but ponies aren't free. :-p
http://en.wikibooks.org/wiki/C%2B%2B_Programming/RTTI is what you're going to get. Reflection like you're thinking about -- fully descriptive metadata available at runtime -- just doesn't exist for C++ by default.
I was able to solve that problem by adding this to my controller method:
$title = 'My Title Here';
View::share('title', $title);
$this->layout->title = 'Home page'; did not work either.
I'm surprised no one has mentioned dnSpy. dnSpy is a debugger and .NET assembly editor. You can use it to edit and debug assemblies even if you don't have any source code available.
Main features:
It is open source and one of most widely used reverse engineering tool for dot net.
The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo
ls
show the right files?git init
? (git-init documentation)Either of those would cause your error.
findIndex works for modern browsers:
var myArr = [{id:'a'},{id:'myid'},{id:'c'}];
var index = myArr.findIndex(function(o){
return o.id === 'myid';
})
if (index !== -1) myArr.splice(index, 1);
If you're still a bit confused about virtualenv
you might not pick up how to combine the great tips from the answers by Ioannis and Sascha. I.e. this is the basic command you need:
/YOUR_ENV/bin/pip freeze --local
That can be easily used elsewhere. E.g. here is a convenient and complete answer, suited for getting all the local packages installed in all the environments you set up via virtualenvwrapper:
cd ${WORKON_HOME:-~/.virtualenvs}
for dir in *; do [ -d $dir ] && $dir/bin/pip freeze --local > /tmp/$dir.fl; done
more /tmp/*.fl
Code summary:
using System.Windows.Forms;
...
MessageBox.Show( "hello world" );
Also (as per this other stack post): In Visual Studio expand the project in Solution Tree, right click on References, Add Reference, Select System.Windows.Forms
on Framework tab. This will get the MessageBox working in conjunction with the using System.Windows.Forms reference from above.
Check this code:
Javascript:
app.config( ["$routeProvider"], function($routeProvider){
$routeProvider.when("/part1", {"templateUrl" : "part1"});
$routeProvider.when("/part2", {"templateUrl" : "part2"});
$routeProvider.otherwise({"redirectTo":"/part1"});
}]
);
function HomeFragmentController($scope) {
$scope.$on("$routeChangeSuccess", function (scope, next, current) {
$scope.transitionState = "active"
});
}
CSS:
.fragmentWrapper {
overflow: hidden;
}
.fragment {
position: relative;
-moz-transition-property: left;
-o-transition-property: left;
-webkit-transition-property: left;
transition-property: left;
-moz-transition-duration: 0.1s;
-o-transition-duration: 0.1s;
-webkit-transition-duration: 0.1s;
transition-duration: 0.1s
}
.fragment:not(.active) {
left: 540px;
}
.fragment.active {
left: 0px;
}
Main page HTML:
<div class="fragmentWrapper" data-ng-view data-ng-controller="HomeFragmentController">
</div>
Partials HTML example:
<div id="part1" class="fragment {{transitionState}}">
</div>
Adding a fixed width to td,th after making tbody & thead display block works perfectly and also we can use slimscroll plugin to make the scroll bar beautiful.
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title> Scrollable table </title>_x000D_
<style>_x000D_
body {_x000D_
font-family: sans-serif;_x000D_
font-size: 0.9em;_x000D_
}_x000D_
table {_x000D_
border-collapse: collapse;_x000D_
border-bottom: 1px solid #ddd;_x000D_
}_x000D_
thead {_x000D_
background-color: #333;_x000D_
color: #fff;_x000D_
}_x000D_
thead,tbody {_x000D_
display: block;_x000D_
}_x000D_
th,td {_x000D_
padding: 8px 10px;_x000D_
border: 1px solid #ddd;_x000D_
width: 117px;_x000D_
box-sizing: border-box;_x000D_
}_x000D_
tbody {_x000D_
height: 160px;_x000D_
overflow-y: scroll_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<table class="example-table">_x000D_
<thead>_x000D_
<tr>_x000D_
<th> Header 1 </th>_x000D_
<th> Header 2 </th>_x000D_
<th> Header 3 </th>_x000D_
<th> Header 4 </th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td> Row 1- Col 1 </td>_x000D_
<td> Row 1- Col 2 </td>_x000D_
<td> Row 1- Col 3 </td>_x000D_
<td> Row 1- Col 4 </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td> Row 2- Col 1 </td>_x000D_
<td> Row 2- Col 2 </td>_x000D_
<td> Row 2- Col 3 </td>_x000D_
<td> Row 2- Col 4 </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td> Row 3- Col 1 </td>_x000D_
<td> Row 3- Col 2 </td>_x000D_
<td> Row 3- Col 3 </td>_x000D_
<td> Row 3- Col 4 </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td> Row 4- Col 1 </td>_x000D_
<td> Row 4- Col 2 </td>_x000D_
<td> Row 4- Col 3 </td>_x000D_
<td> Row 4- Col 4 </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td> Row 5- Col 1 </td>_x000D_
<td> Row 5- Col 2 </td>_x000D_
<td> Row 5- Col 3 </td>_x000D_
<td> Row 5- Col 4 </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td> Row 6- Col 1 </td>_x000D_
<td> Row 6- Col 2 </td>_x000D_
<td> Row 6- Col 3 </td>_x000D_
<td> Row 6- Col 4 </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td> Row 7- Col 1 </td>_x000D_
<td> Row 7- Col 2 </td>_x000D_
<td> Row 7- Col 3 </td>_x000D_
<td> Row 7- Col 4 </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td> Row 8- Col 1 </td>_x000D_
<td> Row 8- Col 2 </td>_x000D_
<td> Row 8- Col 3 </td>_x000D_
<td> Row 8- Col 4 </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td> Row 9- Col 1 </td>_x000D_
<td> Row 9- Col 2 </td>_x000D_
<td> Row 9- Col 3 </td>_x000D_
<td> Row 9- Col 4 </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td> Row 10- Col 1 </td>_x000D_
<td> Row 10- Col 2 </td>_x000D_
<td> Row 10- Col 3 </td>_x000D_
<td> Row 10- Col 4 </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td> Row 11- Col 1 </td>_x000D_
<td> Row 11- Col 2 </td>_x000D_
<td> Row 11- Col 3 </td>_x000D_
<td> Row 11- Col 4 </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td> Row 12- Col 1 </td>_x000D_
<td> Row 12- Col 2 </td>_x000D_
<td> Row 12- Col 3 </td>_x000D_
<td> Row 12- Col 4 </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td> Row 13- Col 1 </td>_x000D_
<td> Row 13- Col 2 </td>_x000D_
<td> Row 13- Col 3 </td>_x000D_
<td> Row 13- Col 4 </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td> Row 14- Col 1 </td>_x000D_
<td> Row 14- Col 2 </td>_x000D_
<td> Row 14- Col 3 </td>_x000D_
<td> Row 14- Col 4 </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td> Row 15- Col 1 </td>_x000D_
<td> Row 15- Col 2 </td>_x000D_
<td> Row 15- Col 3 </td>_x000D_
<td> Row 15- Col 4 </td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td> Row 16- Col 1 </td>_x000D_
<td> Row 16- Col 2 </td>_x000D_
<td> Row 16- Col 3 </td>_x000D_
<td> Row 16- Col 4 </td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery-slimScroll/1.3.8/jquery.slimscroll.min.js"></script>_x000D_
<script>_x000D_
$('.example-table tbody').slimscroll({_x000D_
height: '160px',_x000D_
alwaysVisible: true,_x000D_
color: '#333'_x000D_
})_x000D_
</script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
StringEscapeUtils.escapeXml()
does not escape control characters (< 0x20). XML 1.1 allows control characters; XML 1.0 does not. For example, XStream.toXML()
will happily serialize a Java object's control characters into XML, which an XML 1.0 parser will reject.
To escape control characters with Apache commons-lang, use
NumericEntityEscaper.below(0x20).translate(StringEscapeUtils.escapeXml(str))
I used the display:inline-block property: the solution consist in use a wrapper with fixed width. Inside, the ul block with the inline-block for display. Using this, the ul just take the width for the real content! and finally margin: 0 auto, to center this inline-block =)
/*ul wrapper*/
.gallery_wrapper{
width: 958px;
margin: 0 auto;
}
/*ul list*/
ul.gallery_carrousel{
display: inline-block;
margin: 0 auto;
}
.contenido_secundario li{
float: left;
}
As of Android N, in order to work around this issue, you need to use the FileProvider API
There are 3 main steps here as mentioned below
Step 1: Manifest Entry
<manifest ...>
<application ...>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
</application>
</manifest>
Step 2: Create XML file res/xml/provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
Step 3: Code changes
File file = ...;
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
// Old Approach
install.setDataAndType(Uri.fromFile(file), mimeType);
// End Old approach
// New Approach
Uri apkURI = FileProvider.getUriForFile(
context,
context.getApplicationContext()
.getPackageName() + ".provider", file);
install.setDataAndType(apkURI, mimeType);
install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// End New Approach
context.startActivity(install);
vUsing adjHungarian nnotation vmakes nreading ncode adjdifficult.
You can use Buffer Reader from request to read
// Read from request
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
buffer.append(System.lineSeparator());
}
String data = buffer.toString()
names(x)[names(x) %in% c("q","e")]<-c("A","B")
You can simply use echo -n "|$COMMAND|"
.
How about something like this:
<script>
function changeQueryVariable(keyString, replaceString) {
var query = window.location.search.substring(1);
var vars = query.split("&");
var replaced = false;
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == keyString) {
vars[i] = pair[0] + "="+ replaceString;
replaced = true;
}
}
if (!replaced) vars.push(keyString + "=" + replaceString);
return vars.join("&");
}
</script>
detectScrollbarWidthHeight: function() {
var div = document.createElement("div");
div.style.overflow = "scroll";
div.style.visibility = "hidden";
div.style.position = 'absolute';
div.style.width = '100px';
div.style.height = '100px';
document.body.appendChild(div);
return {
width: div.offsetWidth - div.clientWidth,
height: div.offsetHeight - div.clientHeight
};
},
Tested in Chrome, FF, IE8, IE11.
Replace below characters
~ ! @ # $ % ^ & * ( ) _ +
` - =
{ } |
[ ] \
: "
; '
< > ?
, .
with this SQL
SELECT note as note_original,
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(note, '\"', ''),
'.', ''),
'?', ''),
'`', ''),
'<', ''),
'=', ''),
'{', ''),
'}', ''),
'[', ''),
']', ''),
'|', ''),
'\'', ''),
':', ''),
';', ''),
'~', ''),
'!', ''),
'@', ''),
'#', ''),
'$', ''),
'%', ''),
'^', ''),
'&', ''),
'*', ''),
'_', ''),
'+', ''),
',', ''),
'/', ''),
'(', ''),
')', ''),
'-', ''),
'>', ''),
' ', '-'),
'--', '-') as note_changed FROM invheader
substring(int startIndex, int endIndex)
If you don't specify endIndex, the method will return all the characters from startIndex.
startIndex : starting index is inclusive
endIndex : ending index is exclusive
Example:
String str = "abcdefgh"
str.substring(0, 4)
=> abcd
str.substring(4, 6)
=> ef
str.substring(6)
=> gh
You need to update the output of json.load with a_dict and then dump the result. And you cannot append to the file but you need to overwrite it.
{
isloading? progressIos:Container()
progressIos(int i) {
return Container(
color: i == 1
? AppColors.liteBlack
: i == 2 ? AppColors.darkBlack : i == 3 ? AppColors.pinkBtn : '',
child: Center(child: CupertinoActivityIndicator()));
}
}
No need for a separate SELECT...
INSERT INTO table (name)
OUTPUT Inserted.ID
VALUES('bob');
This works for non-IDENTITY columns (such as GUIDs) too
You can use Object.keys(), "which returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop."
You can use any object in place of stats
:
var stats = {_x000D_
a: 3,_x000D_
b: 6,_x000D_
d: 7,_x000D_
erijgolekngo: 35_x000D_
}_x000D_
/* this is the answer here */_x000D_
for (var key in Object.keys(stats)) {_x000D_
var t = Object.keys(stats)[key];_x000D_
console.log(t + " value =: " + stats[t]);_x000D_
}
_x000D_
Finally I got it to work. Steve's answer is right but not for all cases. It fails when that view is being executed from a third schema. For that to work you have to add the grant option:
GRANT SELECT ON [TABLE_NAME] TO [READ_USERNAME] WITH GRANT OPTION;
That way, [READ_USERNAME]
can also grant select privilege over the view to another schema
To install this product you can see this tutorial: OpenCV on Ubuntu
There are listed the packages you need. So, with:
# dpkg -l | grep libcv2
# dpkg -l | grep libhighgui2
and more listed in the url you can find which packages are installed.
With
# dpkg -L libcv2
you can check where are installed
This operative is used for all debian packages.
<?php if ($foo) { ?>
<div class="mydiv">Condition is true</div>
<?php } else { ?>
<div class="myotherdiv">Condition is false</div>
<?php } ?>
Richard Schneider is right. use code below to fetch data from site which is not utf8 charset will get wrong string.
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
}
" i can't vote.so wrote this.
You must declare
int add(int a, int b);
(note to the semicolon)
in a header file and include the file into both files.
Including it into Main.c will tell compiler how the function should be called.
Including into the second file will allow you to check that declaration is valid (compiler would complain if declaration and implementation were not matched).
Then you must compile both *.c files into one project. Details are compiler-dependent.
I don't know how was the plugin the time the question was asked (2009), but I faced the same problem today and solved it this way:
Give your select tag a name attribute. For example in this case
<select name="myselect">
Instead of working with the attribute value="default" in the tag option, disable the default option as suggested by Jeremy Visser or set value=""
<option disabled="disabled">Choose...</option>
or
<option value="">Choose...</option>
Set the plugin validation rule
$( "#YOUR_FORM_ID" ).validate({
rules: {
myselect: { required: true }
}
});
or
<select name="myselect" class="required">
Obs: redsquare's solution works only if you have just one select in your form. If you want his solution to work with more than one select add a name attribute to your select.
Hope it helps! :)
With Firefox and Chrome you can use :
<a href="whatever" target="_parent" onclick="myfunction()">
If myfunction is present both in iframe and in parent, the parent one will be called.
Instead of Tick
event, use Elapsed
event.
timer.Elapsed += new EventHandler(TimerEventProcessor);
and change the signiture of TimerEventProcessor method;
private void TimerEventProcessor(object sender, ElapsedEventArgs e)
{
label1.Text = _counter.ToString();
_counter += 1;
}
html, body {
height:100%;
}
body {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
In case that you have Ubuntu in your machine, the following steps will help you:
Open your terminal and paste: sudo apt-get install php-soap.
Restart your apache2 server in terminal : service apache2 restart.
To check use your php test file again to be seems like mine in step 1.
Your reference to "0x31 = 1" makes me think you're actually trying to convert ASCII values to strings - in which case you should be using something like Encoding.ASCII.GetString(Byte[])
Essentially it means you don't have the index you are trying to reference. For example:
df = pd.DataFrame()
df['this']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #I haven't yet assigned how long df[data] should be!
print(df)
will give me the error you are referring to, because I haven't told Pandas how long my dataframe is. Whereas if I do the exact same code but I DO assign an index length, I don't get an error:
df = pd.DataFrame(index=[0,1,2,3,4])
df['this']=np.nan
df['is']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #since I've properly labelled my index, I don't run into this problem!
print(df)
Hope that answers your question!
Use this:
int get_lines(string file)
{
var lineCount = 0;
using (var stream = new StreamReader(file))
{
while (stream.ReadLine() != null)
{
lineCount++;
}
}
return lineCount;
}
There are two ways to doing the same:
You may set the value of android:divider="#FFCCFF" in layout xml file. With this you also have to specify height of divider like this android:dividerHeight="5px".
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/lvMyList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#FFCCFF"
android:dividerHeight="5px"/>
</LinearLayout>
You may also do this by programmatically...
ListView listView = getListView();
ColorDrawable myColor = new ColorDrawable(
this.getResources().getColor(R.color.myColor)
);
listView.setDivider(myColor);
listView.setDividerHeight();
Try my xsd-viewer available from https://github.com/santhosh-tekuri/jlibs.
//Convert a float to integer_x000D_
_x000D_
Math.floor(5.95)_x000D_
//5_x000D_
_x000D_
Math.ceil(5.95)_x000D_
//6_x000D_
_x000D_
Math.round(5.4)_x000D_
//5_x000D_
_x000D_
Math.round(5.5)_x000D_
//6_x000D_
_x000D_
Math.trunc(5.5)_x000D_
//5_x000D_
_x000D_
//Quick Ways_x000D_
console.log(5.95| 0)_x000D_
console.log(~~5.95) _x000D_
console.log(5.95 >> 0)_x000D_
//5
_x000D_
TL;DR: np.random.shuffle(ndarray)
can do the job.
So, in your case
np.random.shuffle(DataFrame.values)
DataFrame
, under the hood, uses NumPy ndarray as data holder. (You can check from DataFrame source code)
So if you use np.random.shuffle()
, it would shuffles the array along the first axis of a multi-dimensional array. But index of the DataFrame
remains unshuffled.
Though, there are some points to consider.
sklearn.utils.shuffle()
, as user tj89 suggested, can designate random_state
along with another option to control output. You may want that for dev purpose.sklearn.utils.shuffle()
is faster. But WILL SHUFFLE the axis info(index, column) of the DataFrame
along with the ndarray
it contains.between sklearn.utils.shuffle()
and np.random.shuffle()
.
nd = sklearn.utils.shuffle(nd)
0.10793248389381915 sec. 8x faster
np.random.shuffle(nd)
0.8897626010002568 sec
df = sklearn.utils.shuffle(df)
0.3183923360193148 sec. 3x faster
np.random.shuffle(df.values)
0.9357550159329548 sec
Conclusion: If it is okay to axis info(index, column) to be shuffled along with ndarray, use
sklearn.utils.shuffle()
. Otherwise, usenp.random.shuffle()
import timeit
setup = '''
import numpy as np
import pandas as pd
import sklearn
nd = np.random.random((1000, 100))
df = pd.DataFrame(nd)
'''
timeit.timeit('nd = sklearn.utils.shuffle(nd)', setup=setup, number=1000)
timeit.timeit('np.random.shuffle(nd)', setup=setup, number=1000)
timeit.timeit('df = sklearn.utils.shuffle(df)', setup=setup, number=1000)
timeit.timeit('np.random.shuffle(df.values)', setup=setup, number=1000)
It's not clear to me what you want, but I'll mention that the Date class also has a compareTo method, which can be used to determine with one call if two Date objects are equal or (if they aren't equal) which occurs sooner. This allows you to do something like:
switch (today.compareTo(questionDate)) {
case -1: System.out.println("today is sooner than questionDate"); break;
case 0: System.out.println("today and questionDate are equal"); break;
case 1: System.out.println("today is later than questionDate"); break;
default: System.out.println("Invalid results from date comparison"); break;
}
It should be noted that the API docs don't guarantee the results to be -1, 0, and 1, so you may want to use if-elses rather than a switch in any production code. Also, if the second date is null, you'll get a NullPointerException, so wrapping your code in a try-catch may be useful.
This worked for me.
var regex = /( |<([^>]+)>)/ig
, body = tt
, result = body.replace(regex, "");
alert(result);
In February of 2020, Google announced a major upgrade to the built-in Google Apps Script IDE, and it now supports console.log(). So, you can now use both:
Happy coding!
echo '<pre>' . print_r( $myarray, true ) . '</pre>';
From the PHP.net print_r() docs:
When [the second] parameter is set to TRUE, print_r() will return the information rather than print it.
In Windows 7+ the first quotations will be the title to the cmd
window to open the program:
start "title" "C:\path\program.exe"
Formatting your command like the above will temporarily open a cmd
window that goes away as fast as it comes up so you really never see it. It also allows you to open more than one program without waiting for the first one to close first.
Here is a simple example that should let you keep going add somethink that would act as a placeholder to your winform can be TableLayoutPanel
and then just add controls to it
for ( int i = 0; i < COUNT; i++ ) {
Label lblTitle = new Label();
lblTitle.Text = i+"Your Text";
youlayOut.Controls.Add( lblTitle, 0, i );
TextBox txtValue = new TextBox();
youlayOut.Controls.Add( txtValue, 2, i );
}
Code example:
HashMap<Integer,String> h = new HashMap<Integer,String> ();
h.put(null,null);
h.put(null, "a");
System.out.println(h);
Output:
{null=a}
You are doing everything right by using a to_date function and specifying the time. The time is there in the database. The trouble is just that when you select a column of DATE datatype from the database, the default format mask doesn't show the time. If you issue a
alter session set nls_date_format = 'dd/MON/yyyy hh24:mi:ss'
or something similar including a time component, you will see that the time successfully made it into the database.
You can test a string using this regular expression:
function isValid(str){
return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
I searched for a solution as well, and none of the answers I encountered solved the error, Until I found the answer of "ViRuSTriNiTy" to this thread: Undefined reference to 'boost::system::generic_category()'?
according to that answer, try to add these lines to your cmake file:
find_package(Boost 1.55.0 REQUIRED COMPONENTS system filesystem)
include_directories(... ${Boost_INCLUDE_DIRS})
link_directories(... ${Boost_LIBRARY_DIRS})
target_link_libraries(... ${Boost_LIBRARIES})
Two ways
System.getProperty("user.dir");
or this
File currentDirFile = new File(".");
String helper = currentDirFile.getAbsolutePath();
String currentDir = helper.substring(0, helper.length() - currentDirFile.getCanonicalPath().length());//this line may need a try-catch block
The idea is to get the current folder with ".", and then fetch the absolute position to it and remove the filename from it, so from something like
/home/shark/eclipse/workspace/project/src/com/package/name/bin/Class.class
when you remove Class.class you'd get
/home/shark/eclipse/workspace/project/src/com/package/name/bin/
which is kinda what you want.
status 0 appear when an ajax call was cancelled before getting the response by refreshing the page or requesting a URL that is unreachable.
this status is not documented but exist over ajax and makeRequest call's from gadget.io.
I really like AVee's solution with the lowest IP connection metric! But if a second nic with the same metric is installed, the MAC comparison could fail...
Better you store the description of the interface with the MAC. In later comparisons you can identify the right nic by this string. Here is a sample code:
public static string GetMacAndDescription()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration where IPEnabled=true");
IEnumerable<ManagementObject> objects = searcher.Get().Cast<ManagementObject>();
string mac = (from o in objects orderby o["IPConnectionMetric"] select o["MACAddress"].ToString()).FirstOrDefault();
string description = (from o in objects orderby o["IPConnectionMetric"] select o["Description"].ToString()).FirstOrDefault();
return mac + ";" + description;
}
public static string GetMacByDescription( string description)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration where IPEnabled=true");
IEnumerable<ManagementObject> objects = searcher.Get().Cast<ManagementObject>();
string mac = (from o in objects where o["Description"].ToString() == description select o["MACAddress"].ToString()).FirstOrDefault();
return mac;
}
You can change the database name using MySQL interface.
Go to http://www.hostname.com/phpmyadmin
Go to database which you want to rename. Next, go to the operation tab. There you will find the input field to rename the database.
In TypeScript 1.6, user-defined type guard will do the job.
interface Foo {
fooProperty: string;
}
interface Bar {
barProperty: string;
}
function isFoo(object: any): object is Foo {
return 'fooProperty' in object;
}
let object: Foo | Bar;
if (isFoo(object)) {
// `object` has type `Foo`.
object.fooProperty;
} else {
// `object` has type `Bar`.
object.barProperty;
}
And just as Joe Yang mentioned: since TypeScript 2.0, you can even take the advantage of tagged union type.
interface Foo {
type: 'foo';
fooProperty: string;
}
interface Bar {
type: 'bar';
barProperty: number;
}
let object: Foo | Bar;
// You will see errors if `strictNullChecks` is enabled.
if (object.type === 'foo') {
// object has type `Foo`.
object.fooProperty;
} else {
// object has type `Bar`.
object.barProperty;
}
And it works with switch
too.
Use int
function with second parameter 16, to convert a hex string to an integer. Finally, use hex
function to convert it back to a hexadecimal number.
print hex(int("0xAD4", 16) + int("0x200", 16)) # 0xcd4
Instead you could directly do
print hex(int("0xAD4", 16) + 0x200) # 0xcd4
var origParseFloat = parseFloat;
parseFloat = function(str) {
alert("And I'm in your floats!");
return origParseFloat(str);
}
It is not related with Firewall. I had the same issue accessing from office and from mobile. I cleaned the cookies and worked fine. You can read more at https://support.google.com/chromebook/answer/1085581?hl=en
Use watch to see when a variable is written to, rwatch when it is read and awatch when it is read/written from/to, as noted above. However, please note that to use this command, you must break the program, and the variable must be in scope when you've broken the program:
Use the watch command. The argument to the watch command is an expression that is evaluated. This implies that the variabel you want to set a watchpoint on must be in the current scope. So, to set a watchpoint on a non-global variable, you must have set a breakpoint that will stop your program when the variable is in scope. You set the watchpoint after the program breaks.
Please note instead of
public TomcatEmbeddedServletContainerFactory tomcatFactory()
I had to use the following method signature
public EmbeddedServletContainerFactory embeddedServletContainerFactory()
Set following style to set all textbox to uppercase
input {text-transform: uppercase;}
In my case, I had simply changed the way I created a table and inadvertently changed the field name I tried to query. Make sure the field names you reference in the query actually exist in the table/query you are querying.
You should use something like this:
SELECT *
FROM (select salary2.*, rownum rnum from
(select * from salary ORDER BY salary_amount DESC) salary2
where rownum <= 2 )
WHERE rnum >= 2;