To change the XAMPP Apache server port here the procedure :
The default port used by Apache is 80
.
Take a look to all your used ports with Netstat (integrated to XAMPP Control Panel).
Then you can see all used ports and here we see that the 80
port is already used by System
.
Choose a free port number (8012
, for this exemple).
httpd.conf
"This file should be found in
C:\xampp\apache\conf
on Windows or inbin/apache
for Linux.:
Listen 80
ServerName localhost:80
Replace them by:
Listen 8012
ServerName localhost:8012
Save the file.
Access to : http://localhost:8012 for check if it's work.
If not, you must to edit the http-ssl.conf
file as explain in step 3 below. ?
http-ssl.conf
"This file should be found in
C:\xampp\apache\conf\extra
on Windows or see this link for Linux.
Locate the following lines:
Listen 443
<VirtualHost _default_:443>
ServerName localhost:443
Replace them by with a other port number (8013
for this example) :
Listen 8013
<VirtualHost _default_:8013>
ServerName localhost:8013
Save the file.
Restart the Apache Server.
Access to : http://localhost:8012 for check if it's work.
If your want to access localhost without specify the port number in the URL
http://localhost instead of http://localhost:8012.
8012
and 8013
).If this configuration isn't hiding port number in URL it's because your web browser is not configured for. See : Tools ? Options ? General ? Connection Settings... will allow you to choose different ports or change proxy settings.
If step 4 and Web browser configuration are not working for you the only way to do this is to change back to 80, or to install a listener on port 80 (like a proxy) that redirects all your traffic to port 8012.
If you still have this message in Control Panel Console :
Apache Started [Port 80]
xampp-control.exe
file (probably in C:\xampp
)XAMPP.INI
in that directory (so XAMPP.ini
and xampp-control.exe
are in the same directory)Put following lines in the XAMPP.INI
file:
[PORTS]
apache = 8012
Now , you will always get:
Apache started [Port 8012]
Please note that, this is for display purpose only.
It has no relation with your httpd.conf
.
Make sure that the path actually leads to the executables. I'm using version 11 and it did not work until this was set as the path:
C:\Program Files\PostgreSQL\11\bin\bin
Maybe this is how version 11 is structured or I somehow botched the installation but I haven't had a problem since.
if there are more than 2 js function then following two ways can also be implemented:
if you have more than two functions you can group them in if condition
OR
you can write two different if conditions.
1 OnClientClick="var b = validateView(); if (b) ShowDiv1(); if(b) testfunction(); return b">
OR
2 OnClientClick="var b = validateView(); if(b) {
ShowDiv1();
testfunction();
} return b">
Use render method:
<Route exact path="/details/:id" render={(props)=>{
<DetailsPage id={props.match.params.id}/>
}} />
And you should be able to access the id using:
this.props.id
Inside the DetailsPage component
Ran into the problem today, none of the existing answers helped me. Assume you want to deduplicate your table named your_table
.
Step 1: Create a new table with deduped values
If borrowed this code from somewhere else on StackOverflow but can't seem to find it again. It works fine against PostgreSQL. It creates a table your_table_deduped
where (col1, col2)
are unique.
CREATE TABLE your_table_deduped AS
SELECT * FROM your_table WHERE ctid NOT IN
(SELECT ctid FROM
(SELECT ctid, ROW_NUMBER() OVER
(PARTITION BY col1, col2 ORDER BY ctid) AS rnum
FROM your_table) t
WHERE t.rnum > 1);
Step 2: Replace your first table with the deduped copy
We only delete the values in this step, because it allows us to keep the indexes, constraints, etc. in your table.
DELETE FROM your_table;
INSERT INTO your_table
SELECT * FROM your_table_deduped;
Step 3: Delete the deduped copy
DROP TABLE site_daily_kpis_dedup;
And voila, you have deduplicated your table!
When on Ubuntu 18.04 using Python3.6 I have solved the problem doing both:
with open(filename, encoding="utf-8") as lines:
and if you are running the tool as command line:
export LC_ALL=C.UTF-8
Note that if you are in Python2.7 you have do to handle this differently. First you have to set the default encoding:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
and then to load the file you must use io.open
to set the encoding:
import io
with io.open(filename, 'r', encoding='utf-8') as lines:
You still need to export the env
export LC_ALL=C.UTF-8
This solution reads in an input file line by line, writing each line out to a StringBuilder variable. Whenever it encounters a line that matches what you are looking for, it skips writing that one out. Then it deletes file content and put the StringBuilder variable content.
public void removeLineFromFile(String lineToRemove, File f) throws FileNotFoundException, IOException{
//Reading File Content and storing it to a StringBuilder variable ( skips lineToRemove)
StringBuilder sb = new StringBuilder();
try (Scanner sc = new Scanner(f)) {
String currentLine;
while(sc.hasNext()){
currentLine = sc.nextLine();
if(currentLine.equals(lineToRemove)){
continue; //skips lineToRemove
}
sb.append(currentLine).append("\n");
}
}
//Delete File Content
PrintWriter pw = new PrintWriter(f);
pw.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(f, true));
writer.append(sb.toString());
writer.close();
}
OK, let's first see what would happens if an array value not exist in JavaScript, so if we have an array like below:
const arr = [1, 2, 3, 4, 5];
and now we check if 6 is there at index 5 or not:
arr[5];
and we get
undefined
...
So that's basically give us the answer, the best way to check if undefined, so something like this:
if("undefined" === typeof arrayName[index]) {
//array value is not there...
}
It's better NOT doing this in this case:
if(!arrayName[index]) {
//Don't check like this..
}
Because imagine we have this array:
const arr = [0, 1, 2];
and we do:
if(!arr[0]) {
//This get passed, because in JavaScript 0 is falsy
}
So as you see, even 0 is there, it doesn't get recognised, there are few other things which can do the same and make you application buggy, so be careful, I list them all down:
undefined
''
By default, a MariaDB installation has an anonymous user, allowing anyone to log into MariaDB without having to have a user account created for them. This is intended only for testing, and to make the installation go a bit smoother. You should remove them before moving into a production environment.
From the docs:
Modals have two optional sizes, available via modifier classes to be placed on a .modal-dialog
: modal-lg
and modal-sm
(as of 3.1).
Also the modal dialogue will scale itself on small screens (as of 3.1.1).
There are several factors which means there is no binary answer. The question of what is best for performance depends on your environment. By the way, if your single select with an identifier is not sub-second, something may be wrong with your configuration.
The real question to ask is how do you want to access the data. Single selects support late-binding. For example if you only want employee information, you can select from the Employees table. The foreign key relationships can be used to retrieve related resources at a later time and as needed. The selects will already have a key to point to so they should be extremely fast, and you only have to retrieve what you need. Network latency must always be taken into account.
Joins will retrieve all of the data at once. If you are generating a report or populating a grid, this may be exactly what you want. Compiled and optomized joins are simply going to be faster than single selects in this scenario. Remember, Ad-hoc joins may not be as fast--you should compile them (into a stored proc). The speed answer depends on the execution plan, which details exactly what steps the DBMS takes to retrieve the data.
I've encountered a similar scenario. I solved it by adding in this following code just before find_library()
:
set(CMAKE_PREFIX_PATH /the/custom/path/to/your/lib/)
then it can find the library location.
Well all of the above answers are pretty good but here is a small simple function I whipped up. It works pretty well.
function hasClass(el, cn){
var classes = el.classList;
for(var j = 0; j < classes.length; j++){
if(classes[j] == cn){
return true;
}
}
}
Not possible, but you should check to see if border-style
values like inset
, outset
or some other, accomplished the effect you want.. (i doubt it though..)
CSS3 has the border-image properties, but i do not know about support from browsers yet (more info at http://www.css3.info/preview/border-image/)..
WebSockets are implemented with a protocol that involves handshake between client and server. I don't imagine they work very much like normal sockets. Read up on the protocol, and get your application to talk it. Alternatively, use an existing WebSocket library, or .Net4.5beta which has a WebSocket API.
<button id="fwdbtn" style="color:red">Submit</button>
import threading
# global variable x
x = 0
def increment():
"""
function to increment global variable x
"""
global x
x += 1
def thread_task():
"""
task for thread
calls increment function 100000 times.
"""
for _ in range(100000):
increment()
def main_task():
global x
# setting global variable x as 0
x = 0
# creating threads
t1 = threading.Thread(target=thread_task)
t2 = threading.Thread(target=thread_task)
# start threads
t1.start()
t2.start()
# wait until threads finish their job
t1.join()
t2.join()
if __name__ == "__main__":
for i in range(10):
main_task()
print("Iteration {0}: x = {1}".format(i,x))
byte test[] = new byte[3];
test[0] = 0x0A;
test[1] = 0xFF;
test[2] = 0x01;
for (byte theByte : test)
{
System.out.println(Integer.toHexString(theByte));
}
NOTE: test[1] = 0xFF; this wont compile, you cant put 255 (FF) into a byte, java will want to use an int.
you might be able to do...
test[1] = (byte) 0xFF;
I'd test if I was near my IDE (if I was near my IDE I wouln't be on Stackoverflow)
The and operator in a selector is just an empty string, and the or operator is the comma.
There is however no grouping or priority, so you have to repeat one of the conditions:
a=$('[myc=blue][myid="1"],[myc=blue][myid="3"]');
Working example. Notes below.
class Animal {
constructor(public name) {
}
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
move() {
alert(this.name + " is Slithering...");
super.move(5);
}
}
class Horse extends Animal {
move() {
alert(this.name + " is Galloping...");
super.move(45);
}
}
var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
You don't need to manually assign the name to a public variable. Using public name
in the constructor definition does this for you.
You don't need to call super(name)
from the specialised classes.
Using this.name
works.
Notes on use of super
.
This is covered in more detail in section 4.9.2 of the language specification.
The behaviour of the classes inheriting from Animal
is not dissimilar to the behaviour in other languages. You need to specify the super
keyword in order to avoid confusion between a specialised function and the base class function. For example, if you called move()
or this.move()
you would be dealing with the specialised Snake
or Horse
function, so using super.move()
explicitly calls the base class function.
There is no confusion of properties, as they are the properties of the instance. There is no difference between super.name
and this.name
- there is simply this.name
. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.
Adding productFlavors{} to the app build.gradle solved the issue for me. See below:
buildTypes {
release {
...
}
}
productFlavors {
}
If you are using a router then:
Replace server.listen(yourport, 'localhost');
with server.listen(yourport, 'your ipv4 address');
in my machine it is
server.listen(3000, '192.168.0.3');
Make sure your port is forwarded to your ipv4 address.
On Windows Firewall, tick all on Node.js:Server-side JavaScript.
You don't have to add a .
in getElementsByClassName
, i.e.
var multibutton = angular.element(element.getElementsByClassName("multi-files"));
However, when using angular.element
, you do have to use jquery style selectors:
angular.element('.multi-files');
should do the trick.
Also, from this documentation "If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite.""
For people still getting the issue.
I face same problem and seems some .jar file missing.
so try tar -xf apache-jmeter-5.2.1.tgz
in the console rather than just right click unzip. And also, try binary package if source package still has an issue.
this solve my issue (I am using ubuntu)
The window
binding refers to a built-in object provided by the browser. It represents the browser window that contains the document
. Calling its addEventListener
method registers the second argument (callback function) to be called whenever the event described by its first argument occurs.
<p>Some paragraph.</p>
<script>
window.addEventListener("click", () => {
console.log("Test");
});
</script>
Following points should be noted before select window or document to addEventListners
window
or document
but
some events like resize
, and other events related to loading
,
unloading
, and opening/closing
should all be set on the window.A 400 means that the request was malformed. In other words, the data stream sent by the client to the server didn't follow the rules.
In the case of a REST API with a JSON payload, 400's are typically, and correctly I would say, used to indicate that the JSON is invalid in some way according to the API specification for the service.
By that logic, both the scenarios you provided should be 400s.
Imagine instead this were XML rather than JSON. In both cases, the XML would never pass schema validation--either because of an undefined element or an improper element value. That would be a bad request. Same deal here.
For starters
rake db:rollback
will get you back one step
then
rake db:rollback STEP=n
Will roll you back n
migrations where n
is the number of recent migrations you want to rollback.
More references here.
=IF(B2="X",IF(B3="Y", TRUE, FALSE),FALSE)
, and choose to fill green when this is true=IF(B2="X",IF(B3="W", TRUE, FALSE),FALSE)
and choose to fill red when this is true.More details - conditional formatting with a formula applies the format when the formula evaluates to TRUE. You can use a compound IF
formula to return true or false based on the values of any cells.
Code bellow will also check for PASTE event.
Uncomment "ruleSetArr_4" and add(concate) to "ruleSetArr" to allow FLOAT numbers.
Easy copy/paste function. Call it with your input element in parameter.
Example: inputIntTypeOnly($('input[name="inputName"]'))
function inputIntTypeOnly(elm){_x000D_
elm.on("keydown",function(event){_x000D_
var e = event || window.event,_x000D_
key = e.keyCode || e.which,_x000D_
ruleSetArr_1 = [8,9,46], // backspace,tab,delete_x000D_
ruleSetArr_2 = [48,49,50,51,52,53,54,55,56,57], // top keyboard num keys_x000D_
ruleSetArr_3 = [96,97,98,99,100,101,102,103,104,105], // side keyboard num keys_x000D_
ruleSetArr_4 = [17,67,86], // Ctrl & V_x000D_
//ruleSetArr_5 = [110,189,190], add this to ruleSetArr to allow float values_x000D_
ruleSetArr = ruleSetArr_1.concat(ruleSetArr_2,ruleSetArr_3,ruleSetArr_4); // merge arrays of keys_x000D_
_x000D_
if(ruleSetArr.indexOf() !== "undefined"){ // check if browser supports indexOf() : IE8 and earlier_x000D_
var retRes = ruleSetArr.indexOf(key);_x000D_
} else { _x000D_
var retRes = $.inArray(key,ruleSetArr);_x000D_
};_x000D_
if(retRes == -1){ // if returned key not found in array, return false_x000D_
return false;_x000D_
} else if(key == 67 || key == 86){ // account for paste events_x000D_
event.stopPropagation();_x000D_
};_x000D_
_x000D_
}).on('paste',function(event){_x000D_
var $thisObj = $(this),_x000D_
origVal = $thisObj.val(), // orig value_x000D_
newVal = event.originalEvent.clipboardData.getData('Text'); // paste clipboard value_x000D_
if(newVal.replace(/\D+/g, '') == ""){ // if paste value is not a number, insert orig value and ret false_x000D_
$thisObj.val(origVal);_x000D_
return false;_x000D_
} else {_x000D_
$thisObj.val(newVal.replace(/\D+/g, ''));_x000D_
return false;_x000D_
};_x000D_
_x000D_
});_x000D_
};_x000D_
_x000D_
var inptElm = $('input[name="inputName"]');_x000D_
_x000D_
inputIntTypeOnly(inptElm);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<input type="text" name="inputName" value="1">
_x000D_
If you are using Anaconda with python 3.5
, this is a problem in the Anaconda release. (Refer this issue)
You can fix this issue by copying python3.dll
file to Anaconda3
folder (where python.exe
is located)
cmd
, type python --version
to find whether your installation is 64-bit or 32-bitpython3.dll
file to Anaconda3
folderBut if you can move to Anaconda
with python 3.6
you will not face this issue. If it is possible for you, then it is the recommended way..
You may have forgot to remove the semicolon to uncomment that line. For the date.timezone = "US/Central"
line, be sure that there's no semicolon in front of that line.
I ended up doing it like that for my RecyclerView with GridLayoutManager and HeaderView.
In the code below I set a 4dp space between every item(2dp around every single item and 2dp padding around the whole recyclerview).
layout.xml
<android.support.v7.widget.RecyclerView
android:id="@+id/recycleview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="2dp" />
fragment/activity
GridLayoutManager manager = new GridLayoutManager(getContext(), 3);
recyclerView.setLayoutManager(manager);
int spacingInPixels = Utils.dpToPx(2);
recyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels));
SpaceItemDecoration.java
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private int mSpacing;
public SpacesItemDecoration(int spacing) {
mSpacing = spacing;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView recyclerView, RecyclerView.State state) {
outRect.left = mSpacing;
outRect.top = mSpacing;
outRect.right = mSpacing;
outRect.bottom = mSpacing;
}
}
Utils.java
public static int dpToPx(final float dp) {
return Math.round(dp * (Resources.getSystem().getDisplayMetrics().xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
You need convert list
to numpy array
and then reshape
:
df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
a b c
0 1 2 3
1 4 5 6
2 7 8 9
With Spring 4.1 and above, you can return pretty much anything (such as pictures, pdfs, documents, jars, zips, etc) quite simply without any extra dependencies. For example, the following could be a method to return a user's profile picture from MongoDB GridFS:
@RequestMapping(value = "user/avatar/{userId}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<InputStreamResource> downloadUserAvatarImage(@PathVariable Long userId) {
GridFSDBFile gridFsFile = fileService.findUserAccountAvatarById(userId);
return ResponseEntity.ok()
.contentLength(gridFsFile.getLength())
.contentType(MediaType.parseMediaType(gridFsFile.getContentType()))
.body(new InputStreamResource(gridFsFile.getInputStream()));
}
The things to note:
ResponseEntity with InputStreamResource as a return type
ResponseEntity builder style creation
With this method you dont have to worry about autowiring in the HttpServletResponse, throwing an IOException or copying stream data around.
button.setVisibility(View.GONE);
Interesting question.
This would be my approach.
Hope it helps.
What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:
x = ["0", "1", "2"]
y = int(x[0]) #accessing the zeroth element
If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:
x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)
If your list elements are not strings, you'll have to convert them to strings before using str.join
:
x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)
Also, as stated above, make sure that you're not returning a nested list.
<?php
$array = array(11 => 14,
10 => 9,
12 => 7,
13 => 7,
14 => 4,
15 => 6);
echo array_search(max($array), $array);
?>
array_search() return values:
Returns the key for needle if it is found in the array, FALSE otherwise.
If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.
I just ran into this issue when diffing my branch with master. Git returned one 'mode' error when I expected my branch to be identical to master. I fixed by deleting the file and then merging master in again.
First I ran the diff:
git checkout my-branch
git diff master
This returned:
diff --git a/bin/script.sh b/bin/script.sh
old mode 100755
new mode 100644
I then ran the following to fix:
rm bin/script.sh
git merge -X theirs master
After this, git diff
returned no differences between my-branch and master.
The table and fields have the wrong encoding; however, you can convert them to UTF-8.
ALTER TABLE logtest CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE logtest DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE logtest CHANGE title title VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci;
@sedit was on the right path, but it's a bit awkward to define a variable.
The way to do this in bash is to put a dollar sign in front of your single quoted string.
$ echo -e '1\n2\n3'
1
2
3
$ echo -e '1\n2\n3' | sed 's/.*/\t&/g'
t1
t2
t3
$ echo -e '1\n2\n3' | sed $'s/.*/\t&/g'
1
2
3
If your string needs to include variable expansion, you can put quoted strings together like so:
$ timestamp=$(date +%s)
$ echo -e '1\n2\n3' | sed "s/.*/$timestamp"$'\t&/g'
1491237958 1
1491237958 2
1491237958 3
In bash $'string'
causes "ANSI-C expansion". And that is what most of us expect when we use things like \t
, \r
, \n
, etc. From: https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html#ANSI_002dC-Quoting
Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded...
The expanded result is single-quoted, as if the dollar sign had not been present.
I personally think most efforts to avoid bash are silly because avoiding bashisms does NOT* make your code portable. (Your code will be less brittle if you shebang it to bash -eu
than if you try to avoid bash and use sh
[unless you are an absolute POSIX ninja].) But rather than have a religious argument about that, I'll just give you the BEST* answer.
$ echo -e '1\n2\n3' | sed "s/.*/$(printf '\t')&/g"
1
2
3
* BEST answer? Yes, because one example of what most anti-bash shell scripters would do wrong in their code is use echo '\t'
as in @robrecord's answer. That will work for GNU echo, but not BSD echo. That is explained by The Open Group at http://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html#tag_20_37_16 And this is an example of why trying to avoid bashisms usually fail.
If your using PHP this is a easy way to access an array in PHP from an AngularJS POST.
$params = json_decode(file_get_contents('php://input'),true);
It means:
'O' (Python) objects
The first character specifies the kind of data and the remaining characters specify the number of bytes per item, except for Unicode, where it is interpreted as the number of characters. The item size must correspond to an existing type, or an error will be raised. The supported kinds are to an existing type, or an error will be raised. The supported kinds are:
'b' boolean
'i' (signed) integer
'u' unsigned integer
'f' floating-point
'c' complex-floating point
'O' (Python) objects
'S', 'a' (byte-)string
'U' Unicode
'V' raw data (void)
Another answer helps if need check type
s.
Simple solution:
function betweenDates($cmpDate,$startDate,$endDate){
return (date($cmpDate) > date($startDate)) && (date($cmpDate) < date($endDate));
}
If you want to remove all lines in a file from your current line number, use dG
, it will delete all lines (shift g)
mean end of file
A combination of previous 2 answers did the trick. Thanks. A new class which inherits from Button. Note: updateImages() should be called before showing the button.
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
public class ImageButton extends Button {
public void updateImages(final Image selected, final Image unselected) {
final ImageView iv = new ImageView(selected);
this.getChildren().add(iv);
iv.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
iv.setImage(unselected);
}
});
iv.setOnMouseReleased(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
iv.setImage(selected);
}
});
super.setGraphic(iv);
}
}
That's basically it. These are the methods I use to convert to and from Unix epoch time:
public static DateTime ConvertFromUnixTimestamp(double timestamp)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
return origin.AddSeconds(timestamp);
}
public static double ConvertToUnixTimestamp(DateTime date)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
TimeSpan diff = date.ToUniversalTime() - origin;
return Math.Floor(diff.TotalSeconds);
}
Update: As of .Net Core 2.1 and .Net Standard 2.1 a DateTime equal to the Unix Epoch can be obtained from the static DateTime.UnixEpoch
.
One gotcha arises when you want to instantiate a public type defined in an external package and that type embeds other types that are private.
Example:
package animals
type otherProps{
Name string
Width int
}
type Duck{
Weight int
otherProps
}
How do you instantiate a Duck
in your own program? Here's the best I could come up with:
package main
import "github.com/someone/animals"
func main(){
var duck animals.Duck
// Can't instantiate a duck with something.Duck{Weight: 2, Name: "Henry"} because `Name` is part of the private type `otherProps`
duck.Weight = 2
duck.Width = 30
duck.Name = "Henry"
}
I'd the similar problem and excluding the DataSourceAutoConfiguration and HibernateJpaAutoConfiguration solved the problem.
I have added these two lines in my application.properties file and it worked.
> spring.autoconfigure.exclude[0]=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
> spring.autoconfigure.exclude[1]=org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
While searching for a solution to this problem, I found a variation on GONeale's answer through Patrick Desjardins' blog:
public int Update(T entity, Expression<Func<T, object>>[] properties)
{
DatabaseContext.Entry(entity).State = EntityState.Unchanged;
foreach (var property in properties)
{
var propertyName = ExpressionHelper.GetExpressionText(property);
DatabaseContext.Entry(entity).Property(propertyName).IsModified = true;
}
return DatabaseContext.SaveChangesWithoutValidation();
}
"As you can see, it takes as its second parameter an expression of a function. This will let use this method by specifying in a Lambda expression which property to update."
...Update(Model, d=>d.Name);
//or
...Update(Model, d=>d.Name, d=>d.SecondProperty, d=>d.AndSoOn);
( A somewhat similar solution is also given here: https://stackoverflow.com/a/5749469/2115384 )
The method I am currently using in my own code, extended to handle also (Linq) Expressions of type ExpressionType.Convert
. This was necessary in my case, for example with Guid
and other object properties. Those were 'wrapped' in a Convert() and therefore not handled by System.Web.Mvc.ExpressionHelper.GetExpressionText
.
public int Update(T entity, Expression<Func<T, object>>[] properties)
{
DbEntityEntry<T> entry = dataContext.Entry(entity);
entry.State = EntityState.Unchanged;
foreach (var property in properties)
{
string propertyName = "";
Expression bodyExpression = property.Body;
if (bodyExpression.NodeType == ExpressionType.Convert && bodyExpression is UnaryExpression)
{
Expression operand = ((UnaryExpression)property.Body).Operand;
propertyName = ((MemberExpression)operand).Member.Name;
}
else
{
propertyName = System.Web.Mvc.ExpressionHelper.GetExpressionText(property);
}
entry.Property(propertyName).IsModified = true;
}
dataContext.Configuration.ValidateOnSaveEnabled = false;
return dataContext.SaveChanges();
}
Your program should work exactly the same with either import java.util.*; or import java.util.Date;. There has to be something else you did in between.
Think of it like an archive. MyDB.Bak contains MyDB.mdf and MyDB.ldf.
Restore with Move to say HerDB basically grabs MyDB.mdf (and ldf) from the back up, and copies them as HerDB.mdf and ldf.
So if you already had a MyDb on the server instance you are restoring to it wouldn't be touched.
like this?
docker run -p 3306:3306 -e MYSQL_ALLOW_EMPTY_PASSWORD=yes -d mysql --default-authentication-plugin=mysql_native_password
mysql -uroot --protocol tcp
https://github.com/GitHub30/docs/blob/change-default_authentication_plugin/mysql/stack.yml
or You shoud use MySQL Workbench 8.0.11.
First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.
Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.
Instead, I would move all of the "application" content to a separate component, like a JPanel
for example and simply move this between the applet or frame as required...
ps- You can use f.setLocationRelativeTo(null)
to center the window on the screen ;)
Updated
You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...
Within the constructor of GalzyTable2
you are doing...
JApplet app = new JApplet(); add(app); app.init(); app.start();
...Why are you adding another applet to an applet??
Case in point...
Within the main
method, you are trying to add the instance of JFrame
to itself...
f.getContentPane().add(f, button2);
Instead, create yourself a class that extends from something like JPanel
, add your UI logical to this, using compound components if required.
Then, add this panel to whatever top level container you need.
Take the time to read through Creating a GUI with Swing
Updated with example
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class GalaxyTable2 extends JPanel { private static final int PREF_W = 700; private static final int PREF_H = 600; String[] columnNames = {"Phone Name", "Brief Description", "Picture", "price", "Buy"}; // Create image icons ImageIcon Image1 = new ImageIcon( getClass().getResource("s1.png")); ImageIcon Image2 = new ImageIcon( getClass().getResource("s2.png")); ImageIcon Image3 = new ImageIcon( getClass().getResource("s3.png")); ImageIcon Image4 = new ImageIcon( getClass().getResource("s4.png")); ImageIcon Image5 = new ImageIcon( getClass().getResource("note.png")); ImageIcon Image6 = new ImageIcon( getClass().getResource("note2.png")); ImageIcon Image7 = new ImageIcon( getClass().getResource("note3.png")); Object[][] rowData = { {"Galaxy S", "3G Support,CPU 1GHz", Image1, 120, false}, {"Galaxy S II", "3G Support,CPU 1.2GHz", Image2, 170, false}, {"Galaxy S III", "3G Support,CPU 1.4GHz", Image3, 205, false}, {"Galaxy S4", "4G Support,CPU 1.6GHz", Image4, 230, false}, {"Galaxy Note", "4G Support,CPU 1.4GHz", Image5, 190, false}, {"Galaxy Note2 II", "4G Support,CPU 1.6GHz", Image6, 190, false}, {"Galaxy Note 3", "4G Support,CPU 2.3GHz", Image7, 260, false},}; MyTable ss = new MyTable( rowData, columnNames); // Create a table JTable jTable1 = new JTable(ss); public GalaxyTable2() { jTable1.setRowHeight(70); add(new JScrollPane(jTable1), BorderLayout.CENTER); JPanel buttons = new JPanel(); JButton button = new JButton("Home"); buttons.add(button); JButton button2 = new JButton("Confirm"); buttons.add(button2); add(buttons, BorderLayout.SOUTH); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } public void actionPerformed(ActionEvent e) { new AMainFrame7().setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new GalaxyTable2()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
You also seem to have a lack of understanding about how to use layout managers.
Take the time to read through Creating a GUI with Swing and Laying components out in a container
I needed to make a ListView
with items of different colors. I modified Shardul's method a bit and result in this:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, colorString) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = (TextView) super.getView(position, convertView, parent);
textView.setBackgroundColor(assignBackgroundColor(position));
textView.setTextColor(assignTextColor(position));
return textView;
}
};
colorList.setAdapter(adapter);
assignBackgroundColor()
and assignTextColor()
are methods that assign color you want. They can be replaced with int[]
arrays.
If anyone try to capitalize the every word separate by space...
CREATE FUNCTION response(name VARCHAR(40)) RETURNS VARCHAR(200) DETERMINISTIC
BEGIN
set @m='';
set @c=0;
set @l=1;
while @c <= char_length(name)-char_length(replace(name,' ','')) do
set @c = @c+1;
set @p = SUBSTRING_INDEX(name,' ',@c);
set @k = substring(name,@l,char_length(@p)-@l+1);
set @l = char_length(@k)+2;
set @m = concat(@m,ucase(left(@k,1)),lcase(substring(@k,2)),' ');
end while;
return trim(@m);
END;
CREATE PROCEDURE updateNames()
BEGIN
SELECT response(name) AS name FROM names;
END;
Result
+--------------+
| name |
+--------------+
| Abdul Karim |
+--------------+
In visual Studio 2008, the following works.
Find the AssemblyInfo.cs file and find these 2 lines:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
You could try changing this to:
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.*")]
But this won't give you the desired result, you will end up with a Product Version of 1.0.* and a File Version of 1.0.0.0. Not what you want!
However, if you remove the second of these lines and just have:
[assembly: AssemblyVersion("1.0.*")]
Then the compiler will set the File Version to be equal to the Product Version and you will get your desired result of an automatically increment product and file version which are in sync. E.g. 1.0.3266.92689
I solve this problem from a different perspective.
I think if the server sends JSON data with Content-Type: text/html
header. It doesn't mean the server guy intended to send you some html but accidentally changed to JSON. It does mean the server guy just doesn't care about what the Content-Type
header is. So if the server guy doesn't care as the client side you better ignore the Content-Type
header as well. To ignore the Content-Type
header check in AFNetworking
manager.responseSerializer.acceptableContentTypes = nil;
In this way the AFJSONResponseSerializer
(the default one) will serialize the JSON data without checking Content-Type
in response header.
You had it nearly right in the last line. You want
str(bytes_string, 'utf-8')
because the type of bytes_string
is bytes
, the same as the type of b'abc'
.
First you need to understand, that both are different things. Stored Procedures
are best used for INSERT-UPDATE-DELETE
statements. Whereas Views
are used for SELECT
statements. You should use both of them.
In views you cannot alter the data. Some databases have updatable Views where you can use INSERT-UPDATE-DELETE
on Views
.
Maybe an example from ruby can help:
You can include the mixin Comparable
and define one function "<=>(other)"
, the mixin provides all those functions:
<(other)
>(other)
==(other)
<=(other)
>=(other)
between?(other)
It does this by invoking <=>(other)
and giving back the right result.
"instance <=> other"
returns 0 if both objects are equal, less than 0 if instance
is bigger than other
and more than 0 if other
is bigger.
I would suggest a more "abstract" classification. Add a new class "img-center" which can be used in combination with .img-responsive class:
// Center responsive images
.img-responsive.img-center {
margin: 0 auto;
}
In Angular 6, .angular-cli.json
has been replaced with angular.json
For Angular < 6:
Create a new file with name '.angular-cli.json' and add this file in your main directory.
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"project": {
"name": "my-app"
},
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": [
"assets",
"favicon.ico"
],
"index": "index.html",
"main": "main.ts",
"polyfills": "polyfills.ts",
"test": "test.ts",
"tsconfig": "tsconfig.app.json",
"testTsconfig": "tsconfig.spec.json",
"prefix": "app",
"styles": [
"styles.css"
],
"scripts": [],
"environmentSource": "environments/environment.ts",
"environments": {
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}
],
"e2e": {
"protractor": {
"config": "./protractor.conf.js"
}
},
"lint": [
{
"project": "src/tsconfig.app.json",
"exclude": "**/node_modules/**"
},
{
"project": "src/tsconfig.spec.json",
"exclude": "**/node_modules/**"
},
{
"project": "e2e/tsconfig.e2e.json",
"exclude": "**/node_modules/**"
}
],
"test": {
"karma": {
"config": "./karma.conf.js"
}
},
"defaults": {
"styleExt": "css",
"component": {}
}
}
sdkmanager
(for advanced users / CI):You can find the download links for all individual packages, including various revisions, in the repository XML file: https://dl.google.com/android/repository/repository-12.xml
(where 12 is the version of the repository index and will increase in the future).
All <sdk:url>
values are relative to https://dl.google.com/android/repository
, so
<sdk:url>platform-27_r03.zip</sdk:url>
can be downloaded at https://dl.google.com/android/repository/platform-27_r03.zip
Similar summary XML files exist for system images as well:
Here are two functions to calculate distance and bearing, which are based on the code in previous messages and https://gist.github.com/jeromer/2005586 (added tuple type for geographical points in lat, lon format for both functions for clarity). I tested both functions and they seem to work right.
#coding:UTF-8
from math import radians, cos, sin, asin, sqrt, atan2, degrees
def haversine(pointA, pointB):
if (type(pointA) != tuple) or (type(pointB) != tuple):
raise TypeError("Only tuples are supported as arguments")
lat1 = pointA[0]
lon1 = pointA[1]
lat2 = pointB[0]
lon2 = pointB[1]
# convert decimal degrees to radians
lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r
def initial_bearing(pointA, pointB):
if (type(pointA) != tuple) or (type(pointB) != tuple):
raise TypeError("Only tuples are supported as arguments")
lat1 = radians(pointA[0])
lat2 = radians(pointB[0])
diffLong = radians(pointB[1] - pointA[1])
x = sin(diffLong) * cos(lat2)
y = cos(lat1) * sin(lat2) - (sin(lat1)
* cos(lat2) * cos(diffLong))
initial_bearing = atan2(x, y)
# Now we have the initial bearing but math.atan2 return values
# from -180° to + 180° which is not what we want for a compass bearing
# The solution is to normalize the initial bearing as shown below
initial_bearing = degrees(initial_bearing)
compass_bearing = (initial_bearing + 360) % 360
return compass_bearing
pA = (46.2038,6.1530)
pB = (46.449, 30.690)
print haversine(pA, pB)
print initial_bearing(pA, pB)
document.getElementById("txtBillingGroupName").value = groupName;
Typically there are three types:
From a container to the host
docker cp container_id:./bar/foo.txt .
From the host to a container
docker exec -i container_id sh -c 'cat > ./bar/foo.txt' < ./foo.txt
Second approach to copy from host to container:
docker cp foo.txt mycontainer:/foo.txt
From a container to a container mixes 1 and 2
docker cp container_id1:./bar/foo.txt .
docker exec -i container_id2 sh -c 'cat > ./bar/foo.txt' < ./foo.txt
Try this:
<img src="Runtime Path to photo" border="1" height="64" width="64" object-fit="cover">
Adding object-fit="cover" will force the image to take up the space without losing the aspect ratio.
Once you instantiate a class (using new), that instantiated thing becomes an object. An object is something that can adhere to encapsulation, polymorphism, abstraction principles of object oriented programming and the real thing a program interacts with to consume the instance members defined in class. Object contains instance members (non-static members).
Thus instance of a class is an object. The word ‘instance’ is used when you are referring to the origin from where it born, it's more clearer if you say ‘instance of a class’ compared to ‘object of a class’ (although the latter can be used to).
Can also read the 'Inner classes' section of this java document on nested classes - https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
I think the answer by jpmc26, while by no means wrong, comes down too heavily on circular imports. They can work just fine, if you set them up correctly.
The easiest way to do so is to use import my_module
syntax, rather than from my_module import some_object
. The former will almost always work, even if my_module
included imports us back. The latter only works if my_object
is already defined in my_module
, which in a circular import may not be the case.
To be specific to your case: Try changing entities/post.py
to do import physics
and then refer to physics.PostBody
rather than just PostBody
directly. Similarly, change physics.py
to do import entities.post
and then use entities.post.Post
rather than just Post
.
Heres a simple example taken from the python 2.6 documentation:
import logging
LOG_FILENAME = '/tmp/logging_example.out'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,)
logging.debug('This message should go to the log file')
Database files cannot be reduced in size. While "repairing" database, it is only possible for mongo server to delete some of its files. If large amount of data has been deleted, mongo server will "release" (delete), during repair, some of its existing files.
Right-click My Computer and go to Properties->Advanced->Environmental Variables...
What's above are user variables, and below are system variables. The elements are combined when creating the environment for an application. System variables are shared for all users, but user variables are only for your account/profile.
If you deleted the system ones by accident, bring up the Registry Editor, then go to HKLM\ControlSet002\Control\Session Manager\Environment
(assuming your current control set is not ControlSet002
). Then find the Path
value and copy the data into the Path
value of HKLM\CurrentControlSet\Control\Session Manager\Environment
. You might need to reboot the computer. (Hopefully, these backups weren't from too long ago, and they contain the info you need.)
Well no, from an iOS developer prospective, there are two links that I know of that will open the Maps app on the iPhone
On iOS 5 and lower: http://maps.apple.com?q=xxxx
On iOS 6 and up: http://maps.google.com?q=xxxx
And that's only on Safari. Chrome will direct you to Google Maps webpage.
Other than that you'll need to use a URL scheme that basically beats the purpose because no android will know that protocol.
You might want to know, Why Safari opens the Maps app and Chrome directs me to a webpage?
Well, because safari is the build in browser made by apple and can detect the URL above. Chrome is "just another app" and must comply to the iOS Ecosystem. Therefor the only way for it to communicate with other apps is by using URL schemes.
As mentioned by Dan Abramov
Do it right inside render
We actually use that approach with memoise one for any kind of proxying props to state calculations.
Our code looks this way
// ./decorators/memoized.js
import memoizeOne from 'memoize-one';
export function memoized(target, key, descriptor) {
descriptor.value = memoizeOne(descriptor.value);
return descriptor;
}
// ./components/exampleComponent.js
import React from 'react';
import { memoized } from 'src/decorators';
class ExampleComponent extends React.Component {
buildValuesFromProps() {
const {
watchedProp1,
watchedProp2,
watchedProp3,
watchedProp4,
watchedProp5,
} = this.props
return {
value1: buildValue1(watchedProp1, watchedProp2),
value2: buildValue2(watchedProp1, watchedProp3, watchedProp5),
value3: buildValue3(watchedProp3, watchedProp4, watchedProp5),
}
}
@memoized
buildValue1(watchedProp1, watchedProp2) {
return ...;
}
@memoized
buildValue2(watchedProp1, watchedProp3, watchedProp5) {
return ...;
}
@memoized
buildValue3(watchedProp3, watchedProp4, watchedProp5) {
return ...;
}
render() {
const {
value1,
value2,
value3
} = this.buildValuesFromProps();
return (
<div>
<Component1 value={value1}>
<Component2 value={value2}>
<Component3 value={value3}>
</div>
);
}
}
The benefits of it are that you don't need to code tons of comparison boilerplate inside getDerivedStateFromProps
or componentWillReceiveProps
and you can skip copy-paste initialization inside a constructor.
NOTE:
This approach is used only for proxying the props to state, in case you have some inner state logic it still needs to be handled in component lifecycles.
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
DateTime d = Calendar1.SelectedDate;
// int a;
TextBox2.Text = d.ToShortDateString();
string s = Convert.ToDateTime(TextBox2.Text).ToShortDateString();
string s1 = Convert.ToDateTime(Label7.Text).ToShortDateString();
DateTime dt = Convert.ToDateTime(s).Date;
DateTime dt1 = Convert.ToDateTime(s1).Date;
if (dt <= dt1)
{
Response.Write("<script>alert(' Not a valid Date to extend warranty')</script>");
}
else
{
string diff = dt.Subtract(dt1).ToString();
Response.Write(diff);
Label18.Text = diff;
Session["diff"] = Label18.Text;
}
}
jQuery offers $.inArray
:
Note that inArray returns the index of the element found, so 0
indicates the element is the first in the array. -1
indicates the element was not found.
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = $.inArray('specialword', categoriesPresent) > -1;_x000D_
var foundNotPresent = $.inArray('specialword', categoriesNotPresent) > -1;_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Edit 3.5 years later
$.inArray
is effectively a wrapper for Array.prototype.indexOf
in browsers that support it (almost all of them these days), while providing a shim in those that don't. It is essentially equivalent to adding a shim to Array.prototype
, which is a more idiomatic/JSish way of doing things. MDN provides such code. These days I would take this option, rather than using the jQuery wrapper.
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = categoriesPresent.indexOf('specialword') > -1;_x000D_
var foundNotPresent = categoriesNotPresent.indexOf('specialword') > -1;_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
Edit another 3 years later
Gosh, 6.5 years?!
The best option for this in modern Javascript is Array.prototype.includes
:
var found = categories.includes('specialword');
No comparisons and no confusing -1
results. It does what we want: it returns true
or false
. For older browsers it's polyfillable using the code at MDN.
var categoriesPresent = ['word', 'word', 'specialword', 'word'];_x000D_
var categoriesNotPresent = ['word', 'word', 'word'];_x000D_
_x000D_
var foundPresent = categoriesPresent.includes('specialword');_x000D_
var foundNotPresent = categoriesNotPresent.includes('specialword');_x000D_
_x000D_
console.log(foundPresent, foundNotPresent); // true false
_x000D_
Use ajax, a simple example,
HTML
<button id="button">Get Data</button>
Javascript
var button = document.getElementById("button");
button.addEventListener("click" ajaxFunction, false);
var ajaxFunction = function () {
// ajax code here
}
Alternatively look into jquery ajax
http://api.jquery.com/jQuery.ajax/
To inject an Object, its class must be known to the CDI mechanism. Usualy adding the @Named annotation will do the trick.
I have some additional needs related to this post that sizeToFit
does not solve. I needed to keep the button centered in it's original location, regardless of the text. I also never want the button to be larger than its original size.
So, I layout the button for its maximum size, save that size in the Controller and use the following method to size the button when the text changes:
+ (void) sizeButtonToText:(UIButton *)button availableSize:(CGSize)availableSize padding:(UIEdgeInsets)padding {
CGRect boundsForText = button.frame;
// Measures string
CGSize stringSize = [button.titleLabel.text sizeWithFont:button.titleLabel.font];
stringSize.width = MIN(stringSize.width + padding.left + padding.right, availableSize.width);
// Center's location of button
boundsForText.origin.x += (boundsForText.size.width - stringSize.width) / 2;
boundsForText.size.width = stringSize.width;
[button setFrame:boundsForText];
}
In NodeJS, we have Buffers available, and string conversion with them is really easy. Better, it's easy to convert a Uint8Array to a Buffer. Try this code, it's worked for me in Node for basically any conversion involving Uint8Arrays:
let str = Buffer.from(uint8arr.buffer).toString();
We're just extracting the ArrayBuffer from the Uint8Array and then converting that to a proper NodeJS Buffer. Then we convert the Buffer to a string (you can throw in a hex or base64 encoding if you want).
If we want to convert back to a Uint8Array from a string, then we'd do this:
let uint8arr = new Uint8Array(Buffer.from(str));
Be aware that if you declared an encoding like base64 when converting to a string, then you'd have to use Buffer.from(str, "base64")
if you used base64, or whatever other encoding you used.
This will not work in the browser without a module! NodeJS Buffers just don't exist in the browser, so this method won't work unless you add Buffer functionality to the browser. That's actually pretty easy to do though, just use a module like this, which is both small and fast!
I happen to be stuck with an FTP server (Rackspace Cloud Sites virtual server) that doesn't seem to support MLSD. Yet I need several fields of file information, such as size and timestamp, not just the filename, so I have to use the DIR command. On this server, the output of DIR looks very much like the OP's. In case it helps anyone, here's a little Python class that parses a line of such output to obtain the filename, size and timestamp.
import datetime
class FtpDir:
def parse_dir_line(self, line):
words = line.split()
self.filename = words[8]
self.size = int(words[4])
t = words[7].split(':')
ts = words[5] + '-' + words[6] + '-' + datetime.datetime.now().strftime('%Y') + ' ' + t[0] + ':' + t[1]
self.timestamp = datetime.datetime.strptime(ts, '%b-%d-%Y %H:%M')
Not very portable, I know, but easy to extend or modify to deal with various different FTP servers.
Problem occurs when we want to import CommonJS module into ES6 module codebase.
Before these flags we had to import CommonJS modules with star (* as something
) import:
// node_modules/moment/index.js
exports = moment
// index.ts file in our app
import * as moment from 'moment'
moment(); // not compliant with es6 module spec
// transpiled js (simplified):
const moment = require("moment");
moment();
We can see that *
was somehow equivalent to exports
variable. It worked fine, but it wasn't compliant with es6 modules spec. In spec, the namespace record in star import (moment
in our case) can be only a plain object, not callable (moment()
is not allowed).
With flag esModuleInterop
we can import CommonJS modules in compliance with es6
modules spec. Now our import code looks like this:
// index.ts file in our app
import moment from 'moment'
moment(); // compliant with es6 module spec
// transpiled js with esModuleInterop (simplified):
const moment = __importDefault(require('moment'));
moment.default();
It works and it's perfectly valid with es6 modules spec, because moment
is not namespace from star import, it's default import.
But how does it work? As you can see, because we did a default import, we called the default
property on a moment
object. But we didn't declare a default
property on the exports
object in the moment library. The key is the __importDefault
function. It assigns module (exports
) to the default
property for CommonJS modules:
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
As you can see, we import es6 modules as they are, but CommonJS modules are wrapped into an object with the default
key. This makes it possible to import defaults on CommonJS modules.
__importStar
does the similar job - it returns untouched esModules, but translates CommonJS modules into modules with a default
property:
// index.ts file in our app
import * as moment from 'moment'
// transpiled js with esModuleInterop (simplified):
const moment = __importStar(require("moment"));
// note that "moment" is now uncallable - ts will report error!
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
And what about allowSyntheticDefaultImports
- what is it for? Now the docs should be clear:
Allow default imports from modules with no default export. This does not affect code emit, just typechecking.
In moment
typings we don't have specified default export, and we shouldn't have, because it's available only with flag esModuleInterop
on. So allowSyntheticDefaultImports
will not report an error if we want to import default from a third-party module which doesn't have a default export.
You can try this to get your combination:
as.numeric(rbind(test$x, test$y))
which will return:
26, 34, 21, 29, 20, 28
On Windows systems in order to get wget you may
Simply use this:
this.Invoke((MethodInvoker)delegate
{
YourControl.Property= value; // runs thread safe
});
Here is an approach for you to do something on a different thread and start listening to the key pressed in a different thread. And the Console will stop its processing when your actual process ends or the user terminates the process by pressing Esc key.
class SplitAnalyser
{
public static bool stopProcessor = false;
public static bool Terminate = false;
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Split Analyser starts");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Press Esc to quit.....");
Thread MainThread = new Thread(new ThreadStart(startProcess));
Thread ConsoleKeyListener = new Thread(new ThreadStart(ListerKeyBoardEvent));
MainThread.Name = "Processor";
ConsoleKeyListener.Name = "KeyListener";
MainThread.Start();
ConsoleKeyListener.Start();
while (true)
{
if (Terminate)
{
Console.WriteLine("Terminating Process...");
MainThread.Abort();
ConsoleKeyListener.Abort();
Thread.Sleep(2000);
Thread.CurrentThread.Abort();
return;
}
if (stopProcessor)
{
Console.WriteLine("Ending Process...");
MainThread.Abort();
ConsoleKeyListener.Abort();
Thread.Sleep(2000);
Thread.CurrentThread.Abort();
return;
}
}
}
public static void ListerKeyBoardEvent()
{
do
{
if (Console.ReadKey(true).Key == ConsoleKey.Escape)
{
Terminate = true;
}
} while (true);
}
public static void startProcess()
{
int i = 0;
while (true)
{
if (!stopProcessor && !Terminate)
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Processing...." + i++);
Thread.Sleep(3000);
}
if(i==10)
stopProcessor = true;
}
}
}
These will also redirect both:
yourcommand &> /dev/null
yourcommand >& /dev/null
though the bash manual says the first is preferred.
WHERE dates BETWEEN (convert(datetime, '2012-12-12',110) AND (convert(datetime, '2012-12-12',110))
You could use a Polygon Clipping algorithm to find the intersection between two polygons. However these tend to be complicated algorithms when all of the edge cases are taken into account.
One implementation of polygon clipping that you can use your favorite search engine to look for is Weiler-Atherton. wikipedia article on Weiler-Atherton
Alan Murta has a complete implementation of a polygon clipper GPC.
Edit:
Another approach is to first divide each polygon into a set of triangles, which are easier to deal with. The Two-Ears Theorem by Gary H. Meisters does the trick. This page at McGill does a good job of explaining triangle subdivision.
I had the examples of Android 8 and was trying to use Android 7 SDK. When I closed the project and reopened the application folder and chose to use Android 8 SDK, it was able to find the R file. Hope this helps.
I was able to read a 4GB log file in about 50 seconds with the following. You may be able to make it faster by loading it as a C# assembly dynamically using PowerShell.
[System.IO.StreamReader]$sr = [System.IO.File]::Open($file, [System.IO.FileMode]::Open)
while (-not $sr.EndOfStream){
$line = $sr.ReadLine()
}
$sr.Close()
If the question isn't just "how to access an integer form of the timedelta?" but "how to convert the timedelta column in the dataframe to an int?" the answer might be a little different. In addition to the .dt.days
accessor you need either df.astype
or pd.to_numeric
Either of these options should help:
df['tdColumn'] = pd.to_numeric(df['tdColumn'].dt.days, downcast='integer')
or
df['tdColumn'] = df['tdColumn'].dt.days.astype('int16')
This does the trick:
function findAncestor (el, cls) {
while ((el = el.parentElement) && !el.classList.contains(cls));
return el;
}
The while loop waits until el
has the desired class, and it sets el
to el
's parent every iteration so in the end, you have the ancestor with that class or null
.
Here's a fiddle, if anyone wants to improve it. It won't work on old browsers (i.e. IE); see this compatibility table for classList. parentElement
is used here because parentNode
would involve more work to make sure that the node is an element.
You can use javascript's indexOf function.
var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
alert(str2 + " found");
}
OK, creating a data:URI definitely does the trick for me, thanks to Matthew and Dennkster pointing that option out! Here is basically how I do it:
1) get all the content into a string called "content" (e.g. by creating it there initially or by reading innerHTML of the tag of an already built page).
2) Build the data URI:
uriContent = "data:application/octet-stream," + encodeURIComponent(content);
There will be length limitations depending on browser type etc., but e.g. Firefox 3.6.12 works until at least 256k. Encoding in Base64 instead using encodeURIComponent might make things more efficient, but for me that was ok.
3) open a new window and "redirect" it to this URI prompts for a download location of my JavaScript generated page:
newWindow = window.open(uriContent, 'neuesDokument');
That's it.
Another possibility is too many threads. We just ran into this error message when running a test harness against an app that uses a thread pool. We used
watch -n 5 -d "ps -eL <java_pid> | wc -l"
to watch the ongoing count of Linux native threads running within the given Java process ID. After this hit about 1,000 (for us--YMMV), we started getting the error message you mention.
Run select query on same table with all where
conditions you are applying in update query.
There is a lot of partial information on this page, but not a complete one. Here is what I do:
<DIV id='container'>
that I put all of my content inHere is an example:
html {
background: #a9e4f7; /* Old browsers */
background: -moz-linear-gradient(-45deg, #a9e4f7 0%, #0fb4e7 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, right bottom, color-stop(0%,#a9e4f7), color-stop(100%,#0fb4e7)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(-45deg, #a9e4f7 0%,#0fb4e7 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(-45deg, #a9e4f7 0%,#0fb4e7 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(-45deg, #a9e4f7 0%,#0fb4e7 100%); /* IE10+ */
background: linear-gradient(135deg, #a9e4f7 0%,#0fb4e7 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#a9e4f7', endColorstr='#0fb4e7',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */
background-attachment: fixed;
}
body {
margin-top: 0px;
margin-bottom: 0px;
}
/* OPTIONAL: div to store content. Many of these attributes should be changed to suit your needs */
#container
{
width: 800px;
margin: auto;
background-color: white;
border: 1px solid gray;
border-top: none;
border-bottom: none;
box-shadow: 3px 0px 20px #333;
padding: 10px;
}
This has been tested with IE, Chrome, and Firefox on pages of various sizes and scrolling needs.
You can't do it by C#, but you can edit MSIL.
IL code of your Main method:
.method private hidebysig static void Main() cil managed
{
.entrypoint
.maxstack 1
.locals init (
[0] class MsilEditing.A a)
L_0000: nop
L_0001: newobj instance void MsilEditing.B::.ctor()
L_0006: stloc.0
L_0007: ldloc.0
L_0008: callvirt instance void MsilEditing.A::X()
L_000d: nop
L_000e: ret
}
You should change opcode in L_0008 from callvirt to call
L_0008: call instance void MsilEditing.A::X()
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String reverse1;
String reverse2;
int count = 0;
while(n > 0)
{
String A = sc.next();
String B = sc.next();
reverse1 = new StringBuffer(A).reverse().toString();
reverse2 = new StringBuffer(B).reverse().toString();
if(!A.equals(reverse1))
{
for(int i = 0; i < A.length(); i++)
{
for(int j = 0; j < A.length(); j++)
{
if(A.charAt(j) == A.charAt(i))
{
count++;
}
}
if(count % 2 != 0)
{
A.replace(A.charAt(i),"");
count = 0;
}
}
System.out.println(A);
}
n--;
}
}
}
In my module i am exporting classes this way:
export { SigninComponent } from './SigninComponent';
export { RegisterComponent } from './RegisterComponent';
This allow me to import multiple classes in file from same module:
import { SigninComponent, RegisterComponent} from "../auth.module";
PS: Of course @Fjut answer is correct, but same time it doesn't support multiple imports from same file. I would suggest to use both answers for your needs. But importing from module makes folder structure refactorings more easier.
In Ruby, using selenium-webdriver (2.32.1), there is a page_source
method that contains the entire page source.
In other words, you want to pipe stdout into one filter (tee bbb.out
) and stderr into another filter (tee ccc.out
). There is no standard way to pipe anything other than stdout into another command, but you can work around that by juggling file descriptors.
{ { ./aaa.sh | tee bbb.out; } 2>&1 1>&3 | tee ccc.out; } 3>&1 1>&2
See also How to grep standard error stream (stderr)? and When would you use an additional file descriptor?
In bash (and ksh and zsh), but not in other POSIX shells such as dash, you can use process substitution:
./aaa.sh > >(tee bbb.out) 2> >(tee ccc.out)
Beware that in bash, this command returns as soon as ./aaa.sh
finishes, even if the tee
commands are still executed (ksh and zsh do wait for the subprocesses). This may be a problem if you do something like ./aaa.sh > >(tee bbb.out) 2> >(tee ccc.out); process_logs bbb.out ccc.out
. In that case, use file descriptor juggling or ksh/zsh instead.
My team was hitting a situation with multiple databases on one server, depending on which database you connected to, the ROLE in question was not returned by SELECT * FROM pg_catalog.pg_user
, as proposed by @erwin-brandstetter and @a_horse_with_no_name. The conditional block executed, and we hit role "my_user" already exists
.
Unfortunately we aren't sure of exact conditions, but this solution works around the problem:
DO
$body$
BEGIN
CREATE ROLE my_user LOGIN PASSWORD 'my_password';
EXCEPTION WHEN others THEN
RAISE NOTICE 'my_user role exists, not re-creating';
END
$body$
It could probably be made more specific to rule out other exceptions.
In addition, If you know your code should not work if object is null, you can throw exception by using Optional.orElseThrow
String nullName = null;
String name = Optional.ofNullable(nullName)
.orElseThrow(NullPointerException::new);
// .orElseThrow(CustomException::new);
You are right. String
in java uses concept of String Pool
literal. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.If a string is not immutable, changing the string with one reference will lead to the wrong value for the other references.
I would add one more thing, since String
is immutable, it is safe for multi threading and a single String instance can be shared across different threads. This avoid the usage of synchronization for thread safety, Strings are implicitly thread safe
.
I had the same problem on a rackspeed server after changing the php version in the cpanel. Turned out it also changed the permissions of the folder... I set the permission of the folder to 755 with
chmod 755 folder_name
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>
You should use jquery validation because if you use type="number"
then you can also enter "E" character in input type, which is not correct.
Solution:
HTML
<input class="form-control floatNumber" name="energy1_total_power_generated" type="text" required="" >
JQuery
//integer value validation
$('input.floatNumber').on('input', function() {
this.value = this.value.replace(/[^0-9.]/g,'').replace(/(\..*)\./g, '$1');
});
Will "length" ever deviate from the real length of "s". If the answer is no, then you don't need to store length, because strings store their length already, and you can just call s.Length.
To get the syntax you asked for, you can implement an "implicit" operator like so:
static implicit operator MyStruct(string s) {
return new MyStruct(...);
}
The implicit operator will work, regardless of whether you make your struct mutable or not.
Hi please check the below link
https://www.postgresql.org/docs/current/xfunc-sql.html
EX:
CREATE FUNCTION sum_n_product_with_tab (x int)
RETURNS TABLE(sum int, product int) AS $$
SELECT $1 + tab.y, $1 * tab.y FROM tab;
$$ LANGUAGE SQL;
Another function that would help you look at missing data would be df_status from funModeling library
library(funModeling)
iris.2 is the iris dataset with some added NAs.You can replace this with your dataset.
df_status(iris.2)
This will give you the number and percentage of NAs in each column.
For what its worth, COALESCE is similiar but
IFNULL(expr1, default)
is the exact match you're looking for in DB2.
COALESCE allows multiple arguments, returning the first NON NULL expression, whereas IFNULL only permits the expression and the default.
Thus
SELECT product.ID, IFNULL(product.Name, "Internal") AS ProductName
FROM Product
Gives you what you're looking for as well as the previous answers, just adding for completeness.
The Address property of a cell can get this for you:
MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)
returns A1
.
The other way around can be done with the Row
and Column
property of Range
:
MsgBox Range("A1").Row & ", " & Range("A1").Column
returns 1,1
.
It's all in your error message - seems like unclean shutdown was detected. See http://docs.mongodb.org/manual/tutorial/recover-data-following-unexpected-shutdown/ for detailed information.
In my expirience, usually it helps to run mongod.exe
with --repair
option ro repair DB.
I believe this is a security problem. If I download the jnpl file and execute it after a clean java 8 installation via javaws myfile.jnpl
everything is working fine (I get multiple windows where I have to confirm some security problems).
A better option would be using recursion but the following example can help you to understand logic!
Edit: Correction, recursion will eventually exhaust system out of resources without archiving expected results. The following example it uses simple logic, and it can process very fast...
var sequence = [0,1];_x000D_
var range = 10;_x000D_
_x000D_
for(var i = 0; i < range-2; i++){_x000D_
sequence.push(sequence[i]+sequence[i+1]);_x000D_
}_x000D_
_x000D_
console.log(sequence);
_x000D_
A couple of things wrong here.
Do you really want to open and close the connection for every single log entry?
Shouldn't you be using SqlCommand
instead of SqlDataAdapter
?
The data adapter (or SqlCommand
) needs exactly what the error message tells you it's missing: an active connection. Just because you created a connection object does not magically tell C# that it is the one you want to use (especially if you haven't opened the connection).
I highly recommend a C# / SQL Server tutorial.
FileReader r = new FileReader(file);
Use a file reader load the file and then write its contents to a string buffer.
The link above shows you an example of how to accomplish this. As other post to this answer say to load a file into memory you do not need write access as long as you do not plan on making changes to the actual file.
As others have pointed out, using the * operator for a mutable object duplicates references, so if you change one you change them all. If you want to create independent instances of a mutable object, your xrange syntax is the most Pythonic way to do this. If you are bothered by having a named variable that is never used, you can use the anonymous underscore variable.
[e for _ in xrange(n)]
iCalendar was based on a vCalendar and Outlook 2007 handles both formats well so it doesn't really matters which one you choose.
I'm not sure if this stands for Outlook 2003. I guess you should give it a try.
Outlook's default calendar format is iCalendar (*.ics
)
One more way to add view from Activity
ViewGroup rootLayout = findViewById(android.R.id.content);
rootLayout.addView(view);
Most of the solutions are working but why take so efforts while we also can get mime type very easily. In System.Web assembly, there is method for getting the mime type from file name. eg:
string mimeType = MimeMapping.GetMimeMapping(filename);
Usually I handle my operations within a transaction. As I've experienced, it is not enough to set the context command timeout, but the transaction needs a constructor with a timeout parameter. I had to set both time out values for it to work properly.
int? prevto = uow.Context.Database.CommandTimeout;
uow.Context.Database.CommandTimeout = 900;
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromSeconds(900))) {
...
}
At the end of the function I set back the command timeout to the previous value in prevto.
Using EF6
I use sprint-boot (2.1.1), and mysql version is 8.0.13. I add dependency in pom, solve my problem.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
MySQL Connector/J » 8.0.13 link: https://mvnrepository.com/artifact/mysql/mysql-connector-java/8.0.13
MySQL Connector/J » All the version link:
https://mvnrepository.com/artifact/mysql/mysql-connector-java
You would just use '%' as your wildcard like this:
GRANT ALL ON *.* to root@'192.168.1.%' IDENTIFIED BY 'your-root-password';
Just as Daniel said "Git and TFVC are the two source control options in TFS
". Fortunately both are supported for now in VS Code.
You need to install the Azure Repos Extension for Visual Studio Code. The process of installing is pretty straight forward.
Add the following lines to your user settings
If you have VS 2015 installed on your machine, your path to Team Foundation tool (tf.exe) may look like this:
{ "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\tf.exe", "tfvc.restrictWorkspace": true }
Or for VS 2017:
{ "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\Common7\\IDE\\CommonExtensions\\Microsoft\\TeamFoundation\\Team Explorer\\tf.exe", "tfvc.restrictWorkspace": true }
Open a local folder (repository), From View -> Command Pallette ..., type team signin
Provide user name --> Enter --> Provide password to connect to TFS.
Please refer to below links for more details:
Note that Server Workspaces are not supported:
"TFVC support is limited to Local workspaces":
I found one more answer when there is a constraint layout inside the scroll view then we need to put
android:fillViewport="true"
to the scroll view
and
android:layout_height="0dp"
in the constraint layout
Example:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="0dp">
// Rest of the views
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
If you have a numpy array you can do this:
import numpy as np
from matplotlib import pyplot as plt
data = np.array([
[1, 2],
[2, 3],
[3, 6],
])
x, y = data.T
plt.scatter(x,y)
plt.show()
yes you can use MapView in v2... for further details you can get help from this
https://gist.github.com/joshdholtz/4522551
SomeFragment.java
public class SomeFragment extends Fragment implements OnMapReadyCallback{
MapView mapView;
GoogleMap map;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.some_layout, container, false);
// Gets the MapView from the XML layout and creates it
mapView = (MapView) v.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
return v;
}
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
/*
//in old Api Needs to call MapsInitializer before doing any CameraUpdateFactory call
try {
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
*/
// Updates the location and zoom of the MapView
/*CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
map.animateCamera(cameraUpdate);*/
map.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(43.1, -87.9)));
}
@Override
public void onResume() {
mapView.onResume();
super.onResume();
}
@Override
public void onPause() {
super.onPause();
mapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<permission
android:name="com.example.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.example.permission.MAPS_RECEIVE"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="your_key"/>
<activity
android:name=".HomeActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
some_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<com.google.android.gms.maps.MapView android:id="@+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
Your problem is that you load an external image, meaning from another domain. This causes a security error when you try to access any data of your canvas context.
The C++ way would be to use a std::stringstream
object as:
std::stringstream fmt;
fmt << a << " " << b << " > " << c;
The C way would be to use sprintf
.
The C way is difficult to get right since:
Of course, you may want to fall back on the C way if performance is an issue (imagine you are creating fixed-size million little stringstream
objects and then throwing them away).
With the help of the of Guido mail provided by @kindall, we can understand the standard import process as trying to find the module in each member of sys.path
, and file as the result of this lookup (more details in PyMOTW Modules and Imports.). So if the module is located in an absolute path in sys.path
the result is absolute, but if it is located in a relative path in sys.path
the result is relative.
Now the site.py
startup file takes care of delivering only absolute path in sys.path
, except the initial ''
, so if you don't change it by other means than setting the PYTHONPATH (whose path are also made absolute, before prefixing sys.path
), you will get always an absolute path, but when the module is accessed through the current directory.
Now if you trick sys.path in a funny way you can get anything.
As example if you have a sample module foo.py
in /tmp/
with the code:
import sys
print(sys.path)
print (__file__)
If you go in /tmp you get:
>>> import foo
['', '/tmp', '/usr/lib/python3.3', ...]
./foo.py
When in in /home/user
, if you add /tmp
your PYTHONPATH
you get:
>>> import foo
['', '/tmp', '/usr/lib/python3.3', ...]
/tmp/foo.py
Even if you add ../../tmp
, it will be normalized and the result is the same.
But if instead of using PYTHONPATH
you use directly some funny path
you get a result as funny as the cause.
>>> import sys
>>> sys.path.append('../../tmp')
>>> import foo
['', '/usr/lib/python3.3', .... , '../../tmp']
../../tmp/foo.py
Guido explains in the above cited thread, why python do not try to transform all entries in absolute paths:
we don't want to have to call getpwd() on every import .... getpwd() is relatively slow and can sometimes fail outright,
So your path is used as it is.
I was getting this error while trying to show DatePicker
from Fragment
.
I changed
val datePickerDialog = DatePickerDialog(activity!!.applicationContext, ...)
to
val datePickerDialog = DatePickerDialog(requireContext(), ...)
and it worked just fine.
public int getAge(Date dateOfBirth)
{
Calendar now = Calendar.getInstance();
Calendar dob = Calendar.getInstance();
dob.setTime(dateOfBirth);
if (dob.after(now))
{
throw new IllegalArgumentException("Can't be born in the future");
}
int age = now.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (now.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR))
{
age--;
}
return age;
}
I have written a crontab deploy tool in python: https://github.com/monklof/deploycron
pip install deploycron
Install your crontab is very easy, this will merge the crontab into the system's existing crontab.
from deploycron import deploycron
deploycron(content="* * * * * echo hello > /tmp/hello")
You can do something like req.param('tagId')
Had the same issue then I used the connection string without ./
(like DESKTOP-E53DUML
instead of this ./DESKTOP-E53DUML
)
"Ambiguous column" usually means that the same column name appears in at least two tables; the database engine can't tell which one you want. Use full table names or table aliases to remove the ambiguity.
Here's an example I happened to have in my editor. It's from someone else's problem, but should make sense anyway.
select P.*
from product_has_image P
inner join highest_priority_images H
on (H.id_product = P.id_product and H.priority = p.priority)
http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1230935955 states:
By default, the Arduino IDE and libraries does not use the operator new and operator delete. It does support malloc() and free(). So the solution is to implement new and delete operators for yourself, to use these functions.
Code:
#include <stdlib.h> // for malloc and free void* operator new(size_t size) { return malloc(size); } void operator delete(void* ptr) { free(ptr); }
This let's you create objects, e.g.
C* c; // declare variable
c = new C(); // create instance of class C
c->M(); // call method M
delete(c); // free memory
Regards, tamberg
Kendo grid is good as well as Wijmo. I know Kendo comes with Angular bindings for their datasource and I think Wijmo has an Angular plugin. Neither are free though.
i tried all of the suggested answers, nothing worked for me, so i had to use
jQuery.isEmptyObject()
hoe that helps someone else out with this issue
This is an "old school solution", when MERGE command does not work (I think before version 10).
UPDATE TARGET_TABLE T
SET (T.VAL1, T.VAL2 ) =
(SELECT S.VAL1, S.VAL2
FROM SOURCE_TABLE S
WHERE T.KEY1 = S.KEY1 AND T.KEY2 = S.KEY2)
WHERE EXISTS
(SELECT 1
FROM SOURCE_TABLE S
WHERE T.KEY1 = S.KEY1 AND T.KEY2 = S.KEY2
AND (T.VAL1 <> S.VAL1 OR T.VAL2 <> S.VAL2));
The issue seems to be a windows credentials issue. I was getting the same error on my work laptop with a VPN. I am supposedly logged in as my Domain/Username, which is what I use successfully when connecting directly but as soon as I move to a VPN with another connection I receive this error. I thought it was a DNS issue as I could ping the server but it turns out I needed to run SMSS explicitly as my user from Command prompt.
e.g runas /netonly /user:YourDoman\YourUsername "C:\Program Files (x86)\Microsoft SQL Server Management Studio 18\Common7\IDE\Ssms.exe"
There is no magic solution. C is not a reflective language. Objects don't automatically know what they are.
But you have many choices:
I think this should do it for you.
assertThrows(someException.class, ()-> mockedServiceReference.someMethod(param1,parme2,..));
The way I figured this out was going through the example index.html/style.css that comes packaged with the Fancybox installation.
If you view the code that is used for the demo website and basically copy/paste, you'll be fine.
To get an inline Fancybox working, you will need to have this code present in your index.html file:
<head>
<link href="./fancybox/jquery.fancybox-1.3.4.css" rel="stylesheet" type="text/css" media="screen" />
<script>!window.jQuery && document.write('<script src="jquery-1.4.3.min.js"><\/script>');</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="./fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#various1").fancybox({
'titlePosition' : 'inside',
'transitionIn' : 'none',
'transitionOut' : 'none'
});
});
</script>
</head>
<body>
<a id="various1" href="#inline1" title="Put a title here">Name of Link Here</a>
<div style="display: none;">
<div id="inline1" style="width:400px;height:100px;overflow:auto;">
Write whatever text you want right here!!
</div>
</div>
</body>
Remember to be precise about what folders your script files are placed in and where you are pointing to in the Head tag; they must correspond.
You can convert the QString type to python string by just using the str
function. Assuming you are not using any Unicode characters you can get a python
string as below:
text = str(combobox1.currentText())
If you are using any unicode characters, you can do:
text = unicode(combobox1.currentText())
In newer versions of Eclipse the global configuration file can be set in
Windows > Preferences > Maven > User Settings > Global Settings
Don't beat me why global settings can be configured in user settings... Probably because of the same reason why you need to press "Start" to shutdown your PC on Windows... :D
In TortoiseSVN, you can also Shift + right-click to get a menu that includes "Delete (keep local)".
To solve the error "...cannot be resolved to a type.." do the followings:
It works for me.
Java version to create empty DataSet:
public Dataset<Row> emptyDataSet(){
SparkSession spark = SparkSession.builder().appName("Simple Application")
.config("spark.master", "local").getOrCreate();
Dataset<Row> emptyDataSet = spark.createDataFrame(new ArrayList<>(), getSchema());
return emptyDataSet;
}
public StructType getSchema() {
String schemaString = "column1 column2 column3 column4 column5";
List<StructField> fields = new ArrayList<>();
StructField indexField = DataTypes.createStructField("column0", DataTypes.LongType, true);
fields.add(indexField);
for (String fieldName : schemaString.split(" ")) {
StructField field = DataTypes.createStructField(fieldName, DataTypes.StringType, true);
fields.add(field);
}
StructType schema = DataTypes.createStructType(fields);
return schema;
}
Instead of having static methods and passing around a pointer to the class instance, you could use functionality in the new C++11 standard: std::function
and std::bind
:
#include <functional>
class EventHandler
{
public:
void addHandler(std::function<void(int)> callback)
{
cout << "Handler added..." << endl;
// Let's pretend an event just occured
callback(1);
}
};
The addHandler
method now accepts a std::function
argument, and this "function object" have no return value and takes an integer as argument.
To bind it to a specific function, you use std::bind
:
class MyClass
{
public:
MyClass();
// Note: No longer marked `static`, and only takes the actual argument
void Callback(int x);
private:
int private_x;
};
MyClass::MyClass()
{
using namespace std::placeholders; // for `_1`
private_x = 5;
handler->addHandler(std::bind(&MyClass::Callback, this, _1));
}
void MyClass::Callback(int x)
{
// No longer needs an explicit `instance` argument,
// as `this` is set up properly
cout << x + private_x << endl;
}
You need to use std::bind
when adding the handler, as you explicitly needs to specify the otherwise implicit this
pointer as an argument. If you have a free-standing function, you don't have to use std::bind
:
void freeStandingCallback(int x)
{
// ...
}
int main()
{
// ...
handler->addHandler(freeStandingCallback);
}
Having the event handler use std::function
objects, also makes it possible to use the new C++11 lambda functions:
handler->addHandler([](int x) { std::cout << "x is " << x << '\n'; });
edit 2018-09-13: added some precisions about this pre-flight request and how to avoid it at the end of this reponse.
OPTIONS
requests are what we call pre-flight
requests in Cross-origin resource sharing (CORS)
.
They are necessary when you're making requests across different origins in specific situations.
This pre-flight request is made by some browsers as a safety measure to ensure that the request being done is trusted by the server. Meaning the server understands that the method, origin and headers being sent on the request are safe to act upon.
Your server should not ignore but handle these requests whenever you're attempting to do cross origin requests.
A good resource can be found here http://enable-cors.org/
A way to handle these to get comfortable is to ensure that for any path with OPTIONS
method the server sends a response with this header
Access-Control-Allow-Origin: *
This will tell the browser that the server is willing to answer requests from any origin.
For more information on how to add CORS support to your server see the following flowchart
http://www.html5rocks.com/static/images/cors_server_flowchart.png
edit 2018-09-13
CORS OPTIONS
request is triggered only in somes cases, as explained in MDN docs:
Some requests don’t trigger a CORS preflight. Those are called “simple requests” in this article, though the Fetch spec (which defines CORS) doesn’t use that term. A request that doesn’t trigger a CORS preflight—a so-called “simple request”—is one that meets all the following conditions:
The only allowed methods are:
- GET
- HEAD
- POST
Apart from the headers set automatically by the user agent (for example, Connection, User-Agent, or any of the other headers with names defined in the Fetch spec as a “forbidden header name”), the only headers which are allowed to be manually set are those which the Fetch spec defines as being a “CORS-safelisted request-header”, which are:
- Accept
- Accept-Language
- Content-Language
- Content-Type (but note the additional requirements below)
- DPR
- Downlink
- Save-Data
- Viewport-Width
- Width
The only allowed values for the Content-Type header are:
- application/x-www-form-urlencoded
- multipart/form-data
- text/plain
No event listeners are registered on any XMLHttpRequestUpload object used in the request; these are accessed using the XMLHttpRequest.upload property.
No ReadableStream object is used in the request.
TEXT is a data-type for text based input. On the other hand, you have BLOB and CLOB which are more suitable for data storage (images, etc) due to their larger capacity limits (4GB for example).
As for the difference between BLOB and CLOB, I believe CLOB has character encoding associated with it, which implies it can be suited well for very large amounts of text.
BLOB and CLOB data can take a long time to retrieve, relative to how quick data from a TEXT field can be retrieved. So, use only what you need.
Here is your code for add data into both tableView:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var table1Text: UITextField!
@IBOutlet weak var table2Text: UITextField!
@IBOutlet weak var table1: UITableView!
@IBOutlet weak var table2: UITableView!
var table1Data = ["a"]
var table2Data = ["1"]
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func addData(sender: AnyObject) {
//add your data into tables array from textField
table1Data.append(table1Text.text)
table2Data.append(table2Text.text)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
//reload your tableView
self.table1.reloadData()
self.table2.reloadData()
})
table1Text.resignFirstResponder()
table2Text.resignFirstResponder()
}
//delegate methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == table1 {
return table1Data.count
}else if tableView == table2 {
return table2Data.count
}
return Int()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if tableView == table1 {
let cell = table1.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
let row = indexPath.row
cell.textLabel?.text = table1Data[row]
return cell
}else if tableView == table2 {
let cell = table2.dequeueReusableCellWithIdentifier("Cell1", forIndexPath: indexPath) as! UITableViewCell
let row = indexPath.row
cell.textLabel?.text = table2Data[row]
return cell
}
return UITableViewCell()
}
}
And your result will be:
Download codeblocks-13.12mingw-setup.exe instead of codeblocks-13.12setup.exe from the official site. Here 13.12 is the latest version so far.
Neither isset or property_exists work for me.
I ended up going with:
$exists = array_key_exists($property, get_object_vars($obj));
Example:
class Foo {
public $bar;
function __construct() {
$property = 'bar';
isset($this->$property); // FALSE
property_exists($this, $property); // TRUE
array_key_exists($property, get_object_vars($this)); // TRUE
unset($this->$property);
isset($this->$property); // FALSE
property_exists($this, $property); // TRUE
array_key_exists($property, get_object_vars($this)); // FALSE
$this->$property = 'baz';
isset($this->$property); // TRUE
property_exists($this, $property); // TRUE
array_key_exists($property, get_object_vars($this)); // TRUE
}
}
It is possible to upack without node installed using the following 7-Zip plugin:
http://www.tc4shell.com/en/7zip/asar/
Thanks @MayaPosch for mentioning that in this comment.
Please try this:
<input class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-8 col-md-offset-2" type="text" name="name" value="" placeholder="Your Name" style="background-color:blue;"/>
You basically put all the CSS inside the style part of the input tag and it works.
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 */];
git checkout --[ours/theirs] .
will do what you want, as long as you're at the root of all conflicts. ours/theirs only affects unmerged files so you shouldn't have to grep/find/etc conflicts specifically.
Examples random in the range [1, 10]
val random1 = (0..10).shuffled().last()
or utilizing Java Random
val random2 = Random().nextInt(10) + 1
The latest update with hooks is to use useRouteMatch
.
export default function NestingExample() {
return (
<Router>
<Switch>
<Route path="/topics">
<Topics />
</Route>
</Switch>
</Router>
);
}
function Topics() {
// The `path` lets us build <Route> paths
// while the `url` lets us build relative links.
let { path, url } = useRouteMatch();
return (
<div>
<h2>Topics</h2>
<h5>
<Link to={`${url}/otherpath`}>/topics/otherpath/</Link>
</h5>
<ul>
<li>
<Link to={`${url}/topic1`}>/topics/topic1/</Link>
</li>
<li>
<Link to={`${url}/topic2`}>/topics/topic2</Link>
</li>
</ul>
// You can then use nested routing inside the child itself
<Switch>
<Route exact path={path}>
<h3>Please select a topic.</h3>
</Route>
<Route path={`${path}/:topicId`}>
<Topic />
</Route>
<Route path={`${path}/otherpath`>
<OtherPath/>
</Route>
</Switch>
</div>
);
}
You can use theme_get()
to display the possible options for theme.
You can control the legend font size using:
+ theme(legend.text=element_text(size=X))
replacing X with the desired size.
I recently found and modified this snippet from an existing SO post that I have not been able to find again but I've found it very useful
// specify any elements you've attached listeners to here
const nodes = [document]
// https://developer.mozilla.org/en-US/docs/Web/Events
const logBrowserEvents = () => {
const AllEvents = {
AnimationEvent: ['animationend', 'animationiteration', 'animationstart'],
AudioProcessingEvent: ['audioprocess'],
BeforeUnloadEvent: ['beforeunload'],
CompositionEvent: [
'compositionend',
'compositionstart',
'compositionupdate',
],
ClipboardEvent: ['copy', 'cut', 'paste'],
DeviceLightEvent: ['devicelight'],
DeviceMotionEvent: ['devicemotion'],
DeviceOrientationEvent: ['deviceorientation'],
DeviceProximityEvent: ['deviceproximity'],
DragEvent: [
'drag',
'dragend',
'dragenter',
'dragleave',
'dragover',
'dragstart',
'drop',
],
Event: [
'DOMContentLoaded',
'abort',
'afterprint',
'beforeprint',
'cached',
'canplay',
'canplaythrough',
'change',
'chargingchange',
'chargingtimechange',
'checking',
'close',
'dischargingtimechange',
'downloading',
'durationchange',
'emptied',
'ended',
'error',
'fullscreenchange',
'fullscreenerror',
'input',
'invalid',
'languagechange',
'levelchange',
'loadeddata',
'loadedmetadata',
'noupdate',
'obsolete',
'offline',
'online',
'open',
'open',
'orientationchange',
'pause',
'play',
'playing',
'pointerlockchange',
'pointerlockerror',
'ratechange',
'readystatechange',
'reset',
'seeked',
'seeking',
'stalled',
'submit',
'success',
'suspend',
'timeupdate',
'updateready',
'visibilitychange',
'volumechange',
'waiting',
],
FocusEvent: [
'DOMFocusIn',
'DOMFocusOut',
'Unimplemented',
'blur',
'focus',
'focusin',
'focusout',
],
GamepadEvent: ['gamepadconnected', 'gamepaddisconnected'],
HashChangeEvent: ['hashchange'],
KeyboardEvent: ['keydown', 'keypress', 'keyup'],
MessageEvent: ['message'],
MouseEvent: [
'click',
'contextmenu',
'dblclick',
'mousedown',
'mouseenter',
'mouseleave',
'mousemove',
'mouseout',
'mouseover',
'mouseup',
'show',
],
// https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events
MutationNameEvent: ['DOMAttributeNameChanged', 'DOMElementNameChanged'],
MutationEvent: [
'DOMAttrModified',
'DOMCharacterDataModified',
'DOMNodeInserted',
'DOMNodeInsertedIntoDocument',
'DOMNodeRemoved',
'DOMNodeRemovedFromDocument',
'DOMSubtreeModified',
],
OfflineAudioCompletionEvent: ['complete'],
OtherEvent: ['blocked', 'complete', 'upgradeneeded', 'versionchange'],
UIEvent: [
'DOMActivate',
'abort',
'error',
'load',
'resize',
'scroll',
'select',
'unload',
],
PageTransitionEvent: ['pagehide', 'pageshow'],
PopStateEvent: ['popstate'],
ProgressEvent: [
'abort',
'error',
'load',
'loadend',
'loadstart',
'progress',
],
SensorEvent: ['compassneedscalibration', 'Unimplemented', 'userproximity'],
StorageEvent: ['storage'],
SVGEvent: [
'SVGAbort',
'SVGError',
'SVGLoad',
'SVGResize',
'SVGScroll',
'SVGUnload',
],
SVGZoomEvent: ['SVGZoom'],
TimeEvent: ['beginEvent', 'endEvent', 'repeatEvent'],
TouchEvent: [
'touchcancel',
'touchend',
'touchenter',
'touchleave',
'touchmove',
'touchstart',
],
TransitionEvent: ['transitionend'],
WheelEvent: ['wheel'],
}
const RecentlyLoggedDOMEventTypes = {}
Object.keys(AllEvents).forEach((DOMEvent) => {
const DOMEventTypes = AllEvents[DOMEvent]
if (Object.prototype.hasOwnProperty.call(AllEvents, DOMEvent)) {
DOMEventTypes.forEach((DOMEventType) => {
const DOMEventCategory = `${DOMEvent} ${DOMEventType}`
nodes.forEach((node) => {
node.addEventListener(
DOMEventType,
(e) => {
if (RecentlyLoggedDOMEventTypes[DOMEventCategory]) return
RecentlyLoggedDOMEventTypes[DOMEventCategory] = true
// NOTE: throttle continuous events
setTimeout(() => {
RecentlyLoggedDOMEventTypes[DOMEventCategory] = false
}, 1000)
const isActive = e.target === document.activeElement
// https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement
const hasActiveElement = document.activeElement !== document.body
const msg = [
DOMEventCategory,
'target:',
e.target,
...(hasActiveElement
? ['active:', document.activeElement]
: []),
]
if (isActive) {
console.info(...msg)
}
},
true,
)
})
})
}
})
}
logBrowserEvents()
// export default logBrowserEvents
It'll be easier (and more "proper", see below) if you just run your script as
myprogram /path/to/file
Then you can access the path within the script as $1
(for argument #1, similarly $2
is argument #2, etc.)
file="$1"
externalprogram "$file" [other parameters]
Or just
externalprogram "$1" [otherparameters]
If you want to extract the path from something like --file=/path/to/file
, that's usually done with the getopts
shell function. But that's more complicated than just referencing $1
, and besides, switches like --file=
are intended to be optional. I'm guessing your script requires a file name to be provided, so it doesn't make sense to pass it in an option.
Placing this date_default_timezone_set('Asia/Kolkata');
on config.php above base url also works
PHP List of Supported Time Zones
application/config/config.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
date_default_timezone_set('Asia/Kolkata');
Another way I have found use full is if you wish to set a time zone for each user
Create a MY_Controller.php
create a column in your user table you can name it timezone or any thing you want to. So that way when user selects his time zone it can can be set to his timezone when login.
application/core/MY_Controller.php
<?php
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->set_timezone();
}
public function set_timezone() {
if ($this->session->userdata('user_id')) {
$this->db->select('timezone');
$this->db->from($this->db->dbprefix . 'user');
$this->db->where('user_id', $this->session->userdata('user_id'));
$query = $this->db->get();
if ($query->num_rows() > 0) {
date_default_timezone_set($query->row()->timezone);
} else {
return false;
}
}
}
}
Also to get the list of time zones in php
$timezones = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
foreach ($timezones as $timezone)
{
echo $timezone;
echo "</br>";
}
In addition to @Bergi’s answer, I’d like to offer a third alternative. It's very similar to @Bergi’s 2nd example, but instead of awaiting each readFile
individually, you create an array of promises, each which you await at the end.
import fs from 'fs-promise';
async function printFiles () {
const files = await getFilePaths();
const promises = files.map((file) => fs.readFile(file, 'utf8'))
const contents = await Promise.all(promises)
contents.forEach(console.log);
}
Note that the function passed to .map()
does not need to be async
, since fs.readFile
returns a Promise object anyway. Therefore promises
is an array of Promise objects, which can be sent to Promise.all()
.
In @Bergi’s answer, the console may log file contents in the order they’re read. For example if a really small file finishes reading before a really large file, it will be logged first, even if the small file comes after the large file in the files
array. However, in my method above, you are guaranteed the console will log the files in the same order as the provided array.
This isn't Perl; you don't want to force-fit multiple lines worth of code onto a single line. Write a function, then calling the function takes one line of code.
def read_file(fn):
"""
>>> import os
>>> fn = "/tmp/testfile.%i" % os.getpid()
>>> open(fn, "w+").write("testing")
>>> read_file(fn)
'testing'
>>> os.unlink(fn)
>>> read_file("/nonexistant")
Traceback (most recent call last):
...
IOError: [Errno 2] No such file or directory: '/nonexistant'
"""
with open(fn) as f:
return f.read()
if __name__ == "__main__":
import doctest
doctest.testmod()
create no vim swap file just for a particular file
autocmd bufenter c:/aaa/Dropbox/TapNote/Todo.txt :set noswapfile
If you are using gradle with spring boot and spring JPA then add the below dependency in the build.gradle file
dependencies { compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.1.3.RELEASE'
}
Client side code: I had a requirement where my nodejs webserver should work as both server as well as client, so i added below code when i need it as client, It should work fine, i am using it and working fine for me!!!
const socket = require('socket.io-client')('http://192.168.0.8:5000', {
reconnection: true,
reconnectionDelay: 10000
});
socket.on('connect', (data) => {
console.log('Connected to Socket');
});
socket.on('event_name', (data) => {
console.log("-----------------received event data from the socket io server");
});
//either 'io server disconnect' or 'io client disconnect'
socket.on('disconnect', (reason) => {
console.log("client disconnected");
if (reason === 'io server disconnect') {
// the disconnection was initiated by the server, you need to reconnect manually
console.log("server disconnected the client, trying to reconnect");
socket.connect();
}else{
console.log("trying to reconnect again with server");
}
// else the socket will automatically try to reconnect
});
socket.on('error', (error) => {
console.log(error);
});
Pro-tip Note: for some reason, CSS syntax needs the :active
snippet after the :hover
for the same element in order to be effective
Just be aware of TempData persistence, it's a bit tricky. For example if you even simply read TempData inside the current request, it would be removed and consequently you don't have it for the next request. Instead, you can use Peek
method. I would recommend reading this cool article:
Notepad++ v6.5
Search menu -> Find... -> Mark tab -> Find what: your search text, check Bookmark Line, then Mark All. This will bookmark all the lines with the search term, you'll see the blue circles in the margin.
Then Search menu -> Bookmark -> Remove Bookmarked Lines. This will delete all the bookmarked lines.
You can also use a regex to search. This method won't result in a blank line like John's and will actually delete the line.
Older Versions
Try this:
foreach($array as $k => $obj) {
$obj->{'newKey'} = "value";
}
pStrTemp = [pStrTemp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
<form action="product.php" method="post" name="frmProduct" id="frmProduct" enctype="multipart/form-data">
<input id="submit_value" type="button" name="submit_value" value="">
</form>
<script type="text/javascript">
document.getElementById("submit_value").onclick = submitAction;
function submitAction()
{
document.getElementById("frmProduct").submit();
return false;
}
</script>
EDIT: I accidentally swapped the id's around
Slug is a URL friendly short label for specific content. It only contain Letters, Numbers, Underscores or Hyphens. Slugs are commonly save with the respective content and it pass as a URL string.
Slug can create using SlugField
Ex:
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
If you want to use title as slug, django has a simple function called slugify
from django.template.defaultfilters import slugify
class Article(models.Model):
title = models.CharField(max_length=100)
def slug(self):
return slugify(self.title)
If it needs uniqueness, add unique=True
in slug field.
for instance, from the previous example:
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique=True)
Are you lazy to do slug process ? don't worry, this plugin will help you. django-autoslug
I faced similar issue, with RelativeLayout as the root element for each row in the recyclerview.
To solve the issue, find the xml file that holds each row and make sure that the root element's height is wrap_content
NOT match_parent
.
Your tables should have as immediate children just tbody
and thead
elements, with the rows within*. So, amend the HTML to be:
<table border="1" width="100%" id="test">
<tbody>
<tr>
<td>
<table border="1" width="100%">
<tbody>
<tr>
<td>table 2</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
</tbody>
</table>
Then amend your selector slightly to this:
#test > tbody > tr:last-child { background:#ff0000; }
See it in action here. That makes use of the child selector, which:
...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.
So, you are targeting only direct children of tbody
elements that are themselves direct children of your #test
table.
The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:
#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }
* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:
...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.
It seems the following elegant recursive solution has not been mentioned, although it has been around for a long time. Referring to Knuth's Art of Computer Programming,
mean_1 = x_1, variance_1 = 0; //initial conditions; edge case;
//for k >= 2,
mean_k = mean_k-1 + (x_k - mean_k-1) / k;
variance_k = variance_k-1 + (x_k - mean_k-1) * (x_k - mean_k);
then for a list of n>=2
values, the estimate of the standard deviation is:
stddev = std::sqrt(variance_n / (n-1)).
Hope this helps!
A couple of distinctions that weren't touched on here:
Compare:
exec('ls', $out);
var_dump($out);
// Look an array
$out = shell_exec('ls');
var_dump($out);
// Look -- a string with newlines in it
Conversely, if the output of the command is xml or json, then having each line as part of an array is not what you want, as you'll need to post-process the input into some other form, so in that case use shell_exec.
It's also worth pointing out that shell_exec is an alias for the backtic operator, for those used to *nix.
$out = `ls`;
var_dump($out);
exec also supports an additional parameter that will provide the return code from the executed command:
exec('ls', $out, $status);
if (0 === $status) {
var_dump($out);
} else {
echo "Command failed with status: $status";
}
As noted in the shell_exec manual page, when you actually require a return code from the command being executed, you have no choice but to use exec.
We can modify entrypoint
of a non-running container with the docker run
command.
Example show PATH environment variable:
using bash
and echo
: This answer claims that echo
will not produce any output, which is incorrect.
docker run --rm --entrypoint bash <container> -c 'echo "$PATH"'
using printenv
docker run --rm --entrypoint printenv <container> PATH
When you are sure your script is perfectly working, you can get rid of warning and notices like this: Put this line at the beginning of your PHP script:
error_reporting(E_ERROR);
Before that, when working on your script, I would advise you to properly debug your script so that all notice or warning disappear one by one.
So you should first set it as verbose as possible with:
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
UPDATE: how to log errors instead of displaying them
As suggested in the comments, the better solution is to log errors into a file so only the PHP developer sees the error messages, not the users.
A possible implementation is via the .htaccess file, useful if you don't have access to the php.ini file (source).
# Suppress PHP errors
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_value docref_root 0
php_value docref_ext 0
# Enable PHP error logging
php_flag log_errors on
php_value error_log /home/path/public_html/domain/PHP_errors.log
# Prevent access to PHP error log
<Files PHP_errors.log>
Order allow,deny
Deny from all
Satisfy All
</Files>
dataframe['column'].squeeze()
should solve this. It basically changes the dataframe column to a list.
We have now (jan2017) a csv layer import inside Google Maps itself.
Google Maps > "Your Places" > "Open in My Maps"
I needed to keep the placeholder alignment so adam's answer was not enough for me.
To solve this I used a small variation that I hope will help some of you too:
- (void) drawPlaceholderInRect:(CGRect)rect {
//search field placeholder color
UIColor* color = [UIColor whiteColor];
[color setFill];
[self.placeholder drawInRect:rect withFont:self.font lineBreakMode:UILineBreakModeTailTruncation alignment:self.textAlignment];
}
If you want to set to a new color or prevent the change of the color of a specific link after visiting it, add inside the tag of that link:
<a style="text-decoration:none; color:#ff0000;" href="link.html">test link</a>
Above the color is #ff0000 but you can make it anything you'd like.
Simply add method:
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: UITableViewRowActionStyle.destructive, title: "Delete") { (action, indexPath) in
self.arrayFruit.remove(at: indexPath.row)
self.tblList.reloadData()
}
let edit = UITableViewRowAction(style: UITableViewRowActionStyle.normal, title: "Edit") { (action, indexpath) in
let alert = UIAlertController(title: "FruitApp", message: "Enter Fuit Name", preferredStyle: UIAlertControllerStyle.alert)
alert.addTextField(configurationHandler: { (textField) in
textField.placeholder = "Enter new fruit name"
})
alert.addAction(UIAlertAction(title: "Update", style: UIAlertActionStyle.default, handler: { [weak alert](_) in
let textField = alert?.textFields![0]
self.arrayFruit[indexPath.row] = (textField?.text!)!
self.tblList.reloadData()
}))
self.present(alert, animated: true, completion: nil)
}
edit.backgroundColor = UIColor.blue
return [delete,edit]
}
Because ... it (MILLISECONDS
) is a static field (hiding in an enumeration, but that's what it is) ... however it is being invoked upon an instance of the given type (but see below as this isn't really true1).
javac will "accept" that, but it should really be MyUnits.MILLISECONDS
(or non-prefixed in the applicable scope).
1 Actually, javac "rewrites" the code to the preferred form -- if m
happened to be null
it would not throw an NPE at run-time -- it is never actually invoked upon the instance).
Happy coding.
I'm not really seeing how the question title fits in with the rest :-) More accurate and specialized titles increase the likely hood the question/answers can benefit other programmers.