You don't need a function for it - simply use the bracket notation:
var side = columns['right'];
This is equal to dot notation, var side = columns.right;
, except the fact that right
could also come from a variable, function return value, etc., when using bracket notation.
If you NEED a function for it, here it is:
function read_prop(obj, prop) {
return obj[prop];
}
To answer some of the comments below that aren't directly related to the original question, nested objects can be referenced through multiple brackets. If you have a nested object like so:
var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};
you can access property x
of c
as follows:
var cx = foo['c']['x']
If a property is undefined, an attempt to reference it will return undefined
(not null
or false
):
foo['c']['q'] === null
// returns false
foo['c']['q'] === false
// returns false
foo['c']['q'] === undefined
// returns true
You realise that you may be making a rod for your own back for the future. The pwdencrypt() and pwdcompare() are undocumented functions and may not behave the same in future versions of SQL Server.
Why not hash the password using a predictable algorithm such as SHA-2 or better before hitting the DB?
The most similar C# Select
analogue would be a map
function.
Just use:
var ids = selectedFruits.map(fruit => fruit.id);
to select all ids from selectedFruits
array.
It doesn't require any external dependencies, just pure JavaScript. You can find map
documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
This is the Swift version of David's Objective-C answer. You use the global queue to run things in the background and the main queue to update the UI.
DispatchQueue.global(qos: .background).async {
// Background Thread
DispatchQueue.main.async {
// Run UI Updates
}
}
We can align a view in center of the FrameLayout
by setting the layout_gravity
of the child view.
In XML:
android:layout_gravity="center"
In Java code:
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
Note: use FrameLayout.LayoutParams
not the others existing LayoutParams
You can use linear indexing to access each element.
for idx = 1:numel(array)
element = array(idx)
....
end
This is useful if you don't need to know what i,j,k, you are at. However, if you don't need to know what index you are at, you are probably better off using arrayfun()
In newer browser (excluding IE11), a simple solution to prevent parent-child margin collapsing is to use display: flow-root
. However, you would still need other techniques to prevent adjacent element collapsing.
DEMO (before)
.parent {_x000D_
background-color: grey;_x000D_
}_x000D_
_x000D_
.child {_x000D_
height: 16px;_x000D_
margin-top: 16px;_x000D_
margin-bottom: 16px;_x000D_
background-color: blue;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
</div>
_x000D_
DEMO (after)
.parent {_x000D_
display: flow-root;_x000D_
background-color: grey;_x000D_
}_x000D_
_x000D_
.child {_x000D_
height: 16px;_x000D_
margin-top: 16px;_x000D_
margin-bottom: 16px;_x000D_
background-color: blue;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
</div>
_x000D_
InitialValue="0" : initial validation will fire when 0th index item is selected in ddl.
<asp:RequiredFieldValidator InitialValue="0" Display="Dynamic" CssClass="error" runat="server" ID="your_id" ValidationGroup="validationgroup" ControlToValidate="your_dropdownlist_id" />
Here you can find every thing you need:
http://web.eecs.umich.edu/~sugih/courses/eecs487/glut-howto/#win
In Chrome, request with 'Content-Type:application/json' shows as Request PayedLoad and sends data as json object.
But request with 'Content-Type:application/x-www-form-urlencoded' shows Form Data and sends data as Key:Value Pair, so if you have array of object in one key it flats that key's value:
{ Id: 1,
name:'john',
phones:[{title:'home',number:111111,...},
{title:'office',number:22222,...}]
}
sends
{ Id: 1,
name:'john',
phones:[object object]
phones:[object object]
}
Pim's answer is very helpful. In my case, I have to use
Expires / Max-Age: "Session"
If it is a dateTime, even it is not expired, it still won't send the cookie to the backend:
Expires / Max-Age: "Thu, 21 May 2020 09:00:34 GMT"
Hope it is helpful for future people who may meet same issue.
If you have multiple ul and want to empty specific ul then use id eg:
<ul id="randomName">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<script>
$('#randomName').empty();
</script>
$('input').click(function() {_x000D_
$('#randomName').empty()_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<ul id="randomName">_x000D_
<li>1</li>_x000D_
<li>2</li>_x000D_
<li>3</li>_x000D_
</ul>_x000D_
_x000D_
<ul>_x000D_
<li>4</li>_x000D_
<li>5</li>_x000D_
</ul>_x000D_
<input type="button" value="click me" />
_x000D_
try installing 4.0.30 as mentioned in this documentation: http://developer.android.com/google/play-services/setup.html
The accepted solution didn't work for me but I did some digging on the project settings.
The following solution fixed it for me at least IF you are using a Dynamic Web Project:
You should be able to add the src/main/java. It also automatically adds it to Deployment Assembly.
Caveat: If you added a src/test/java note that it also adds it to Deployment Assembly. Generally, you don't need this. You may remove it.
You have to update your app.config file manually
// Load the app.config file
XmlDocument xml = new XmlDocument();
xml.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
// Do whatever you need, like modifying the appSettings section
// Save the new setting
xml.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
And then tell your application to reload any section you modified
ConfigurationManager.RefreshSection("appSettings");
Were I you I would do something like this:
Before doing anything please keep a copy (better safe than sorry)
git checkout master
git checkout -b temp
git reset --hard <sha-1 of your first commit>
git add .
git commit -m 'Squash all commits in single one'
git push origin temp
After doing that you can delete other branches.
Result: You are going to have a branch with only 2 commits.
Use
git log --oneline
to see your commits in a minimalistic way and to find SHA-1 for commits!
Try to use Puppeteer to create PDF from HTML
Example from here https://github.com/chuongtrh/html_to_pdf
Formatting your data that may be the problem. Try either of these:
data: '{ "things":' + JSON.stringify(things) + '}',
Or (from How can I post an array of string to ASP.NET MVC Controller without a form?)
var postData = { things: things };
...
data = postData
\begin{equation}
\resizebox{.9\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}
or
\begin{equation}
\resizebox{.8\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}
The --trace-ascii
option to curl will show the request headers, as well as the response headers and response body.
For example, the command
curl --trace-ascii curl.trace http://www.google.com/
produces a file curl.trace
that starts as follows:
== Info: About to connect() to www.google.com port 80 (#0)
== Info: Trying 209.85.229.104... == Info: connected
== Info: Connected to www.google.com (209.85.229.104) port 80 (#0)
=> Send header, 145 bytes (0x91)
0000: GET / HTTP/1.1
0010: User-Agent: curl/7.16.3 (powerpc-apple-darwin9.0) libcurl/7.16.3
0050: OpenSSL/0.9.7l zlib/1.2.3
006c: Host: www.google.com
0082: Accept: */*
008f:
It also got a response (a 302 response, to be precise but irrelevant) which was logged.
If you only want to save the response headers, use the --dump-header
option:
curl -D file url
curl --dump-header file url
If you need more information about the options available, use curl --help | less
(it produces a couple hundred lines of output but mentions a lot of options). Or find the manual page where there is more explanation of what the options mean.
Use the str
accessor with square brackets:
df['col'] = df['col'].str[:9]
Or str.slice:
df['col'] = df['col'].str.slice(0, 9)
This is the one-liner I copy-and-paste:
curl https://bootstrap.pypa.io/get-pip.py | python3
Alternate:
curl -L get-pip.io | python3
From Installing with get-pip.py:
To install pip, securely download
get-pip.py
by following this link: get-pip.py. Alternatively, use curl:curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
Then run the following command in the folder where you have downloaded get-pip.py:
python get-pip.py
Warning: Be cautious if you are using a Python install that is managed by your operating system or another package manager. get-pip.py does not coordinate with those tools, and may leave your system in an inconsistent state.
It's important to note that Lauritz's suggestion idea of using bisect does not actually find the closest value in MyList to MyNumber. Instead, bisect finds the next value in order after MyNumber in MyList. So in OP's case you'd actually get the position of 44 returned instead of the position of 4.
>>> myList = [1, 3, 4, 44, 88]
>>> myNumber = 5
>>> pos = (bisect_left(myList, myNumber))
>>> myList[pos]
...
44
To get the value that's closest to 5 you could try converting the list to an array and using argmin from numpy like so.
>>> import numpy as np
>>> myNumber = 5
>>> myList = [1, 3, 4, 44, 88]
>>> myArray = np.array(myList)
>>> pos = (np.abs(myArray-myNumber)).argmin()
>>> myArray[pos]
...
4
I don't know how fast this would be though, my guess would be "not very".
Here is the correct solution to solving this problem:
public void hideProgress() {
if(mProgressDialog != null) {
if(mProgressDialog.isShowing()) { //check if dialog is showing.
//get the Context object that was used to great the dialog
Context context = ((ContextWrapper)mProgressDialog.getContext()).getBaseContext();
//if the Context used here was an activity AND it hasn't been finished or destroyed
//then dismiss it
if(context instanceof Activity) {
if(!((Activity)context).isFinishing() && !((Activity)context).isDestroyed())
mProgressDialog.dismiss();
} else //if the Context used wasnt an Activity, then dismiss it too
mProgressDialog.dismiss();
}
mProgressDialog = null;
}
}
Instead of blindly catching all exceptions, this solution addresses the root of the problem: trying to dimiss a dialog when the activity used to initialize the dialog has already been finished. Working on my Nexus 4 running KitKat, but should work for all versions of Android.
In your case it is probably taking them in DD-MM-YY format, not MM-DD-YY.
You can rename the directory using the file system. Then you can do git rm <old directory>
and git add <new directory>
(Help page). Then you can commit and push.
Git will detect that the contents are the same and that it's just a rename operation, and it'll appear as a rename entry in the history. You can check that this is the case before the commit using git status
The main difference is not what can be modified by the trigger, that depends on the DBMS. A trigger (row or statement level) may modify one or many rows*, of the same or other tables as well and may have cascading effects (trigger other actions/triggers) but all these depend on the DBMS of course.
The main difference is how many times the trigger is activated. Imagine you have a 1M rows table and you run:
UPDATE t
SET columnX = columnX + 1
A statement-level trigger will be activated once (and even if no rows are updated). A row-level trigger will be activated a million times, once for every updated row.
Another difference is the order or activation. For example in Oracle the 4 different types of triggers will be activated in the following order:
Before the triggering statement executes
Before each row that the triggering statement affects
After each row that the triggering statement affects
After the triggering statement executes
In the previous example, we'd have something like:
Before statement-level trigger executes
Before row-level trigger executes
One row is updated
After row-level trigger executes
Before row-level trigger executes
Second row is updated
After row-level trigger executes
...
Before row-level trigger executes
Millionth row is updated
After row-level trigger executes
After statement-level trigger executes
Addendum
* Regarding what rows can be modified by a trigger: Different DBMS have different limitations on this, depending on the specific implementation or triggers in the DBMS. For example, Oracle may show a "mutating table" errors for some cases, e.g. when a row-level trigger selects from the whole table (SELECT MAX(col) FROM tablename
) or if it modifies other rows or the whole table and not only the row that is related to / triggered from.
It is perfectly valid of course for a row-level trigger (in Oracle or other) to modify the row that its change has triggered it and that is a very common use. Example in dbfiddle.uk.
Other DBMS may have different limitations on what any type of trigger can do and even what type of triggers are offered (some do not have BEFORE
triggers for example, some do not have statement level triggers at all, etc).
Call MimeMessage.saveChanges()
on the enclosing message, which will update the headers by cascading down the MIME structure into a call to MimeBodyPart.updateHeaders()
on your body part. It's this updateHeaders
call that transfers the content type from the DataHandler
to the part's MIME Content-Type
header.
When you set the content of a MimeBodyPart
, JavaMail internally (and not obviously) creates a DataHandler
object wrapping the object you passed in. The part's Content-Type
header is not updated immediately.
There's no straightforward way to do it in your test program, since you don't have a containing MimeMessage
and MimeBodyPart.updateHeaders()
isn't public
.
Here's a working example that illuminates expected and unexpected outputs:
public class MailTest {
public static void main( String[] args ) throws Exception {
Session mailSession = Session.getInstance( new Properties() );
Transport transport = mailSession.getTransport();
String text = "Hello, World";
String html = "<h1>" + text + "</h1>";
MimeMessage message = new MimeMessage( mailSession );
Multipart multipart = new MimeMultipart( "alternative" );
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText( text, "utf-8" );
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent( html, "text/html; charset=utf-8" );
multipart.addBodyPart( textPart );
multipart.addBodyPart( htmlPart );
message.setContent( multipart );
// Unexpected output.
System.out.println( "HTML = text/html : " + htmlPart.isMimeType( "text/html" ) );
System.out.println( "HTML Content Type: " + htmlPart.getContentType() );
// Required magic (violates principle of least astonishment).
message.saveChanges();
// Output now correct.
System.out.println( "TEXT = text/plain: " + textPart.isMimeType( "text/plain" ) );
System.out.println( "HTML = text/html : " + htmlPart.isMimeType( "text/html" ) );
System.out.println( "HTML Content Type: " + htmlPart.getContentType() );
System.out.println( "HTML Data Handler: " + htmlPart.getDataHandler().getContentType() );
}
}
You can get at the data values like this:
string json = @"
[
{ ""General"" : ""At this time we do not have any frequent support requests."" },
{ ""Support"" : ""For support inquires, please see our support page."" }
]";
JArray a = JArray.Parse(json);
foreach (JObject o in a.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
string name = p.Name;
string value = (string)p.Value;
Console.WriteLine(name + " -- " + value);
}
}
Fiddle: https://dotnetfiddle.net/uox4Vt
I am not a Bootstrap expert, but it sounds to me that you should define a new class called nohover (or something equivalent) then in your link code add the class as the last attribute value:
<a class="green nohover" href="#">green text</a>
<a class="yellow nohover" href="#">yellow text</a>
Then in your Bootstrap LESS/CSS file, define nohover (using the JSFiddle example above):
a:hover { color: red }
/* Green */
a.green { color: green; }
/* Yellow */
a.yellow { color: yellow; }
a.nohover:hover { color: none; }
Forked the JSFiddle here: http://jsfiddle.net/9rpkq/
Use (eventName)
for while binding event to DOM, basically ()
is used for event binding. Also use ngModel
to get two way binding for myModel
variable.
Markup
<input type="text" [(ngModel)]="myModel" (blur)="onBlurMethod()">
Code
export class AppComponent {
myModel: any;
constructor(){
this.myModel = '123';
}
onBlurMethod(){
alert(this.myModel)
}
}
Alternative(not preferable)
<input type="text" #input (blur)="onBlurMethod($event.target.value)">
For model driven form to fire validation on blur
, you could pass updateOn
parameter.
ctrl = new FormControl('', {
updateOn: 'blur', //default will be change
validators: [Validators.required]
});
In Visual Studio 2008 and Visual Studio 2005 at least, you can specify changes to environment variables in the project settings.
Open your project. Go to Project -> Properties... Under Configuration Properties -> Debugging, edit the 'Environment' value to set environment variables.
For example, if you want to add the directory "c:\foo\bin" to the path when debugging your application, set the 'Environment' value to "PATH=%PATH%;c:\foo\bin".
As others said, Sessions are clever and has more advantage of hiding the information from the client.
But Cookie still has at least one advantage, you can access your Cookies from Javascript(For example ngCookies). With PHP session you can't access it anywhere outside PHP script.
$(document).ready(function () {
toggleFields(); // call this first so we start out with the correct visibility depending on the selected form values
// this will call our toggleFields function every time the selection value of our other field changes
$("#dbType").change(function () {
toggleFields();
});
});
// this toggles the visibility of other server
function toggleFields() {
if ($("#dbType").val() === "other")
$("#otherServer").show();
else
$("#otherServer").hide();
}
HTML:
<p>Choose type</p>
<p>Server:
<select id="dbType" name="dbType">
<option>Choose Database Type</option>
<option value="oracle">Oracle</option>
<option value="mssql">MS SQL</option>
<option value="mysql">MySQL</option>
<option value="other">Other</option>
</select>
</p>
<div id="otherServer">
<p>Server:
<input type="text" name="server_name" />
</p>
<p>Port:
<input type="text" name="port_no" />
</p>
</div>
<p align="center">
<input type="submit" value="Submit!" />
</p>
You need add charset in the RequestMapping annotation:
@RequestMapping(path = "/account", produces = "application/json;charset=UTF-8")
thats all.
Install the View In Browser plugin using Package Control or download package from github and unzip this package in your packages folder(that from browse packages)
after this, go to Preferences, Key Bindings - User, paste this
[{ "keys": [ "f12" ], "command": "view_in_browser" }]
now F12 will be your shortcut key.
First you need to download the URL (as text):
private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
Then you need to parse it (and here you have some options).
GSON (full example):
static class Item {
String title;
String link;
String description;
}
static class Page {
String title;
String link;
String description;
String language;
List<Item> items;
}
public static void main(String[] args) throws Exception {
String json = readUrl("http://www.javascriptkit.com/"
+ "dhtmltutors/javascriptkit.json");
Gson gson = new Gson();
Page page = gson.fromJson(json, Page.class);
System.out.println(page.title);
for (Item item : page.items)
System.out.println(" " + item.title);
}
Outputs:
javascriptkit.com
Document Text Resizer
JavaScript Reference- Keyboard/ Mouse Buttons Events
Dynamically loading an external JavaScript or CSS file
Try the java API from json.org:
try {
JSONObject json = new JSONObject(readUrl("..."));
String title = (String) json.get("title");
...
} catch (JSONException e) {
e.printStackTrace();
}
Added another case to Michal Górny's answer:
Note that relative imports are based on the name of the current module. Since the name of the main module is always "__main__
", modules intended for use as the main module of a Python application must always use absolute imports.
Your XML is not entirely clear, but arrays XML can cause force closes if you make them numbers, and/or put white space in their definition.
Make sure they are defined like No Leading or Trailing Whitespace
In both Visual Basic 6.0 and VB.NET you would use:
Exit For
to break from For loopWend
to break from While loopExit Do
to break from Do loopdepending on the loop type. See Exit Statements for more details.
Free JarCheck tool here
First, you need to create your branch locally
git checkout -b your_branch
After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it
git push -u origin your_branch
Your Teammates/colleagues can push to your branch by doing commits and then push explicitly
... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch
Clear is faster because it does not loop over elements to delete. This method can assume that ALL elements can be deleted.
Remove all
does not necessarily mean delete all elements in the list, only those provided as parameters SHOULD be delete. Hence, more effort is required to keep those which should not be deleted.
CLARIFICATION
By 'loop', I mean it does not have to check whether the element should be kept or not. It can set the reference to null
without searching through the provided lists of elements to delete.
Clear
IS faster than deleteall
.
I'm not sure if I'm missing something here, but there's no reason why you can't add a listener to your panel.
In Netbeans, just hit the "Source" button in the top left of the editor window and you can edit most of the code. The actual layout code is mostly locked, but you can even customize that if you need to.
As far as I'm aware, txtMessage.requestFocusInWindow()
is supposed to set up the default focus for when the window is displayed the first time. If you want to request the focus after the window has been displayed already, you should use txtMessage.requestFocus()
For testing, you can just add a listener in the constructor:
addWindowListener(new WindowAdapter(){
public void windowOpened( WindowEvent e){
txtMessage.requestFocus();
}
});
You should do:
try:
value_index = my_list.index(value)
except:
value_index = -1;
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.
As of AngularJS 1.1.3, you can now do exactly what you want using the new catch-all parameter.
https://github.com/angular/angular.js/commit/7eafbb98c64c0dc079d7d3ec589f1270b7f6fea5
From the commit:
This allows routeProvider to accept parameters that matches substrings even when they contain slashes if they are prefixed with an asterisk instead of a colon. For example, routes like
edit/color/:color/largecode/*largecode
will match with something like thishttp://appdomain.com/edit/color/brown/largecode/code/with/slashs
.
I have tested it out myself (using 1.1.5) and it works great. Just keep in mind that each new URL will reload your controller, so to keep any kind of state, you may need to use a custom service.
I know this question is specific to sql server, but I'm using postgresql and came across this question, so for anybody else in a similar situation, there is the split_part(string text, delimiter text, field int)
function.
Have you installed it?
On debian/ubuntu:
aptitude install python-numpy
On windows:
http://sourceforge.net/projects/numpy/files/NumPy/
On other systems:
http://sourceforge.net/projects/numpy/files/NumPy/
$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install
int day = (int)DateTime.Now.DayOfWeek;
First day of the week: Sunday (with a value of zero)
-Wall
and -Wextra
sets the stage in GCC and the subsequent -Wno-unused-variable
may not take effect. For example, if you have:
CFLAGS += -std=c99 -pedantic -pedantic-errors -Werror -g0 -Os \
-fno-strict-overflow -fno-strict-aliasing \
-Wall -Wextra \
-pthread \
-Wno-unused-label \
-Wno-unused-function \
-Wno-unused-parameter \
-Wno-unused-variable \
$(INC)
then GCC sees the instruction -Wall -Wextra
and seems to ignore -Wno-unused-variable
This can instead look like this below and you get the desired effect of not being stopped in your compile on the unused variable:
CFLAGS += -std=c99 -pedantic -pedantic-errors -Werror -g0 -Os \
-fno-strict-overflow -fno-strict-aliasing \
-pthread \
-Wno-unused-label \
-Wno-unused-function \
$(INC)
There is a good reason it is called a "warning" vs an "error". Failing the compile just because you code is not complete (say you are stubbing the algorithm out) can be defeating.
Per @l3x, it depends.
There are clearly two sets of general situations where the correct answer can be different, along with a third which is not as general:
a) You are a user sending private mails:
Very few modern email systems implement case sensitivity, so you are probably fine to ignore case and choose whatever case you feel like using. There is no guarantee that all your mails will be delivered - but so few mails would be negatively affected that you should not worry about it.
b) You are developing mail software:
See RFC5321 2.4 excerpt at the bottom.
When you are developing mail software, you want to be RFC-compliant. You can make your own users' email addresses case insensitive if you want to (and you probably should). But in order to be RFC compliant, you MUST treat outside addresses as case sensitive.
c) Managing business-owned lists of email addresses as an employee:
It is possible that the same email recipient is added to a list more than once - but using different case. In this situation though the addresses are technically different, it might result in a recipient receiving duplicate emails. How you treat this situation is similar to situation a) in that you are probably fine to treat them as duplicates and to remove a duplicate entry. It is better to treat these as special cases however, by sending a "reminder" mail to both addresses to ask them if the case of the email address is accurate.
From a legal standpoint, if you remove a duplicate without acknowledgement/permission from both addresses, you can be held responsible for leaking private information/authentication to an unauthorised address simply because two actually-separate recipients have the same address with different cases.
Excerpt from RFC5321 2.4:
The local-part of a mailbox MUST BE treated as case sensitive. Therefore, SMTP implementations MUST take care to preserve the case of mailbox local-parts. In particular, for some hosts, the user "smith" is different from the user "Smith". However, exploiting the case sensitivity of mailbox local-parts impedes interoperability and is discouraged.
Added streaming support based on the answer of @dunes:
import re
from json import JSONDecoder, JSONDecodeError
NOT_WHITESPACE = re.compile(r"[^\s]")
def stream_json(file_obj, buf_size=1024, decoder=JSONDecoder()):
buf = ""
ex = None
while True:
block = file_obj.read(buf_size)
if not block:
break
buf += block
pos = 0
while True:
match = NOT_WHITESPACE.search(buf, pos)
if not match:
break
pos = match.start()
try:
obj, pos = decoder.raw_decode(buf, pos)
except JSONDecodeError as e:
ex = e
break
else:
ex = None
yield obj
buf = buf[pos:]
if ex is not None:
raise ex
I am using simple tool for basic sqlite operation called Lita
This tool is based on Adobe Air so that must be installed prior to use of Lita. Adobe air can be downloaded for free from Adobe site.
I've written an Angular directive that does slideToggle()
without jQuery.
You can use the following library:
https://github.com/pnowy/NativeCriteria
The library is built on the top of the Hibernate "create sql query" so it supports all databases supported by Hibernate (the Hibernate session and JPA providers are supported). The builder patter is available and so on (object mappers, result mappers).
You can find the examples on github page, the library is available at Maven central of course.
NativeCriteria c = new NativeCriteria(new HibernateQueryProvider(hibernateSession), "table_name", "alias");
c.addJoin(NativeExps.innerJoin("table_name_to_join", "alias2", "alias.left_column", "alias2.right_column"));
c.setProjection(NativeExps.projection().addProjection(Lists.newArrayList("alias.table_column","alias2.table_column")));
If you just want to get the current UNIX timestamp I'd just use time()
$timestamp = time();
Try getting hold of a URL for your classpath resource:
URL url = this.getClass().getResource("/com/path/to/file.txt")
Then create a file using the constructor that accepts a URI:
File file = new File(url.toURI());
Here's an outline of how you could go about doing this. It should be relatively straightforward to implement it as actual code.
user.name
would become user
and name
. Look up user
in your map to get the object and use reflection to obtain the value of name
from the object. Assuming your objects have standard getters, you will look for a method getName
and invoke it.setTimeout(callback,t)
is used to run callback after at least t millisecond. The actual delay depends on many external factors like OS timer granularity and system load.
So, there is a possibility that it will be called slightly after the set time, but will never be called before.
A timer can't span more than 24.8 days.
I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.
I found a link doing the same thing. Try following these steps.
First rename your module from app to i.e. SurveyApp
Second add this to your project top-level (root project) gradle. It's working with Gradle 3.0
//rename apk for all sub projects
subprojects {
afterEvaluate { project ->
if (project.hasProperty("android")) {
android.applicationVariants.all { variant ->
variant.outputs.all {
outputFileName = "${project.name}-${variant.name}-${variant.versionName}.apk"
}
}
}
}
}
char[] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
Javascript now has a specific built in object called Map, you can call as follows :
var myMap = new Map()
You can update it with .set :
myMap.set("key0","value")
This has the advantage of methods you can use to handle look ups, like the boolean .has
myMap.has("key1"); // evaluates to false
You can use this before calling .get on your Map object to handle looking up non-existent keys
select 'SELECT SETVAL(' || seq [ 1] || ', COALESCE(MAX('||column_name||')+1, 1) ) FROM '||table_name||';'
from (
SELECT table_name, column_name, column_default, regexp_match(column_default, '''.*''') as seq
from information_schema.columns
where column_default ilike 'nextval%'
) as sequense_query
If you are a Windows user, this is a common error when you use XAMPP
since LDAP
is not enabled by default.
You can follow this steps to make sure LDAP
works in your XAMPP
:
[Your Drive]:\xampp\php\php.ini
: In this file uncomment the following line:
extension=php_ldap.dll
Move the file: libsasl.dll
, from [Your Drive]:\xampp\php
to [Your Drive]:\xampp\apache\bin
(Note: moving the file is needed only for XAMPP prior to version: 5.6.28
)
Restart Apache.
You can now use functions of the LDAP Module!
If you use Linux:
For php5:
sudo apt-get install php5-ldap
For php7:
sudo apt-get install php7.0-ldap
If you are using the latest version of PHP you can do
sudo apt-get install php-ldap
running the above command should do the trick.
if for any reason it doesn't work check your php.ini configuration to enable ldap, remove the semicolon before extension=ldap
to uncomment, save and restart Apache
And what about:
if ($('#dataTable[data-timer]').length > 0) {
// logic here
}
If you are planning to use JSONP
you can use getJSON
which made for that. jQuery has helper methods for JSONP
.
$.getJSON( 'http://someotherdomain.com/service.svc&callback=?', function( result ) {
console.log(result);
});
Read the below links
http://api.jquery.com/jQuery.getJSON/
Related to how to link to the README.md
of a GitHub repository to a specific line number of code
You have three cases:
We can link to (custom commit)
But Link will ALWAYS link to old file version, which will NOT contains new updates in the master branch for example. Example:
https://github.com/username/projectname/blob/b8d94367354011a0470f1b73c8f135f095e28dd4/file.txt#L10
We can link to (custom branch) like (master-branch). But the link will ALWAYS link to the latest file version which will contain new updates. Due to new updates, the link may point to an invalid business line number. Example:
https://github.com/username/projectname/blob/master/file.txt#L10
GitHub can NOT make AUTO-link to any file either to (custom commit) nor (master-branch) Because of following business issues:
Thanks @Vincent Robert, I ended up using your basic example, though it's actually newBegin + oldEnd - oldBegin
. Here's the simplified end solution:
// don't update end date if there's already an end date but not an old start date
if (!oldEnd || oldBegin) {
var selectedDateSpan = 1800000; // 30 minutes
if (oldEnd) {
selectedDateSpan = oldEnd - oldBegin;
}
newEnd = new Date(newBegin.getTime() + selectedDateSpan));
}
I have a more complicated situation, the dataset has a nested structure:
import json
data = '{"TextID":{"0":"0038f0569e","1":"003eb6998d","2":"006da49ea0"},"Summary":{"0":{"Crisis_Level":["c"],"Type":["d"],"Special_Date":["a"]},"1":{"Crisis_Level":["d"],"Type":["a","d"],"Special_Date":["a"]},"2":{"Crisis_Level":["d"],"Type":["a"],"Special_Date":["a"]}}}'
df = pd.DataFrame.from_dict(json.loads(data))
print(df)
output:
TextID Summary
0 0038f0569e {'Crisis_Level': ['c'], 'Type': ['d'], 'Specia...
1 003eb6998d {'Crisis_Level': ['d'], 'Type': ['a', 'd'], 'S...
2 006da49ea0 {'Crisis_Level': ['d'], 'Type': ['a'], 'Specia...
The Summary
column contains dict objects, so I use apply
with from_dict
and stack
to extract each row of dict:
df2 = df.apply(
lambda x: pd.DataFrame.from_dict(x[1], orient='index').stack(), axis=1)
print(df2)
output:
Crisis_Level Special_Date Type
0 0 0 1
0 c a d NaN
1 d a a d
2 d a a NaN
Looks good, but missing the TextID
column. To get TextID
column back, I've tried three approach:
Modify apply
to return multiple columns:
df_tmp = df.copy()
df_tmp[['TextID', 'Summary']] = df.apply(
lambda x: pd.Series([x[0], pd.DataFrame.from_dict(x[1], orient='index').stack()]), axis=1)
print(df_tmp)
output:
TextID Summary
0 0038f0569e Crisis_Level 0 c
Type 0 d
Spec...
1 003eb6998d Crisis_Level 0 d
Type 0 a
...
2 006da49ea0 Crisis_Level 0 d
Type 0 a
Spec...
But this is not what I want, the Summary
structure are flatten.
Use pd.concat
:
df_tmp2 = pd.concat([df['TextID'], df2], axis=1)
print(df_tmp2)
output:
TextID (Crisis_Level, 0) (Special_Date, 0) (Type, 0) (Type, 1)
0 0038f0569e c a d NaN
1 003eb6998d d a a d
2 006da49ea0 d a a NaN
Looks fine, the MultiIndex
column structure are preserved as tuple. But check columns type:
df_tmp2.columns
output:
Index(['TextID', ('Crisis_Level', 0), ('Special_Date', 0), ('Type', 0),
('Type', 1)],
dtype='object')
Just as a regular Index
class, not MultiIndex
class.
use set_index
:
Turn all columns you want to preserve into row index, after some complicated apply
function and then reset_index
to get columns back:
df_tmp3 = df.set_index('TextID')
df_tmp3 = df_tmp3.apply(
lambda x: pd.DataFrame.from_dict(x[0], orient='index').stack(), axis=1)
df_tmp3 = df_tmp3.reset_index(level=0)
print(df_tmp3)
output:
TextID Crisis_Level Special_Date Type
0 0 0 1
0 0038f0569e c a d NaN
1 003eb6998d d a a d
2 006da49ea0 d a a NaN
Check the type of columns
df_tmp3.columns
output:
MultiIndex(levels=[['Crisis_Level', 'Special_Date', 'Type', 'TextID'], [0, 1, '']],
codes=[[3, 0, 1, 2, 2], [2, 0, 0, 0, 1]])
So, If your apply
function will return MultiIndex
columns, and you want to preserve it, you may want to try the third method.
SELECT TOP 14 A, B, C
FROM MyDatabase
Where EXISTS
(
Select Distinct[A] FROM MyDatabase
)
Use AFNetworking; Put other parameters in the parameter dictionary and append the image data in form data.
//Upload Image Using AFNetworking
-(BOOL)uploadImageAFNetworkingWithURL:(NSString *)path andImage:(UIImage *)image andImageNameWithExtension:(NSString *)strImageName andParamDict:(NSDictionary *)dictParam andKeyForUploadingImage:(NSString *)keyUplaodImg{
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
NSString *strError = EMPTY_STRING;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:path parameters:dictParam constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:keyUplaodImg fileName:strImageName mimeType:@"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"success = %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error = %@", error);
NSLog(@"Response = %@", operation);
[strError stringByAppendingString:STR_ERR_MESSAGE];
}];
if(strError.length>0){
return NO;
}else{
return YES;
}
}
This will give you sequence of anonymous objects, containing date string and two properties with average price:
var query = from p in PriceLogList
group p by p.LogDateTime.ToString("MMM yyyy") into g
select new {
LogDate = g.Key,
AvgGoldPrice = (int)g.Average(x => x.GoldPrice),
AvgSilverPrice = (int)g.Average(x => x.SilverPrice)
};
If you need to get list of PriceLog objects:
var query = from p in PriceLogList
group p by p.LogDateTime.ToString("MMM yyyy") into g
select new PriceLog {
LogDateTime = DateTime.Parse(g.Key),
GoldPrice = (int)g.Average(x => x.GoldPrice),
SilverPrice = (int)g.Average(x => x.SilverPrice)
};
Are you mixing C and C++? One issue that can occur is that the declarations in the .h
file for a .c
file need to be surrounded by:
#if defined(__cplusplus)
extern "C" { // Make sure we have C-declarations in C++ programs
#endif
and:
#if defined(__cplusplus)
}
#endif
Note: if unable / unwilling to modify the .h
file(s) in question, you can surround their inclusion with extern "C"
:
extern "C" {
#include <abc.h>
} //extern
If you'd like to avoid hard-coding a specific design with css, but rather rely on the browser's default button, you can use the following css.
a.button {
-webkit-appearance: button;
-moz-appearance: button;
appearance: button;
}
Notice that it probably won't work on IE.
You should use adapter.notifyDataSetChanged()
. What does the logs says when you use that?
Pass the mouse over the container and go hovering on the divs I use this for jQuery DropDown menus mainly:
Copy the whole document and create a .html file you'll be able to figure out on your own from that!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>The Divs Case</title>
<style type="text/css">
* {margin:0px auto;
padding:0px;}
.container {width:800px;
height:600px;
background:#FFC;
border:solid #F3F3F3 1px;}
.div01 {float:right;
background:#000;
height:200px;
width:200px;
display:none;}
.div02 {float:right;
background:#FF0;
height:150px;
width:150px;
display:none;}
.div03 {float:right;
background:#FFF;
height:100px;
width:100px;
display:none;}
div.container:hover div.div01 {display:block;}
div.container div.div01:hover div.div02 {display:block;}
div.container div.div01 div.div02:hover div.div03 {display:block;}
</style>
</head>
<body>
<div class="container">
<div class="div01">
<div class="div02">
<div class="div03">
</div>
</div>
</div>
</div>
</body>
</html>
If you consider using numpy
, you can get a faster solution.
import random, time
import numpy as np
a = random.sample(range(1, 20000), 10000)
since = time.time(); b = [i/sum(a) for i in a]; print(time.time()-since)
# 0.7956490516662598
since = time.time(); c=np.array(a);d=c/sum(a); print(time.time()-since)
# 0.001413106918334961
For python 3 use this
inp = list(map(int,input().split()))
#input => java is a programming language
#return as => ("java","is","a","programming","language")
input() accepts a string from STDIN.
split()
splits the string about whitespace character and returns a list of strings.
map()
passes each element of the 2nd argument to the first argument and returns a map object
Finally list()
converts the map to a list
You can also set the test env in your test file as follows:
/* eslint-env jest */
describe(() => {
/* ... */
})
For Swift3
let theString = "<h1>H1 title</h1><b>Logo</b><img src='http://www.aver.com/Images/Shared/logo-color.png'><br>~end~"
let theAttributedString = try! NSAttributedString(data: theString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
UITextView_Message.attributedText = theAttributedString
Personally I prefer SQLObject for this sort of thing. I adapted some quick-and-dirty test code I had to get this:
import simplejson
from sqlobject import *
# Replace this with the URI for your actual database
connection = connectionForURI('sqlite:/:memory:')
sqlhub.processConnection = connection
# This defines the columns for your database table. See SQLObject docs for how it
# does its conversions for class attributes <-> database columns (underscores to camel
# case, generally)
class Song(SQLObject):
name = StringCol()
artist = StringCol()
album = StringCol()
# Create fake data for demo - this is not needed for the real thing
def MakeFakeDB():
Song.createTable()
s1 = Song(name="B Song",
artist="Artist1",
album="Album1")
s2 = Song(name="A Song",
artist="Artist2",
album="Album2")
def Main():
# This is an iterable, not a list
all_songs = Song.select().orderBy(Song.q.name)
songs_as_dict = []
for song in all_songs:
song_as_dict = {
'name' : song.name,
'artist' : song.artist,
'album' : song.album}
songs_as_dict.append(song_as_dict)
print simplejson.dumps(songs_as_dict)
if __name__ == "__main__":
MakeFakeDB()
Main()
So I think I'll finally answer my own question in order to have a full solution for the record. But have to thank Ben James and Kailash Badu which provided the clues for this.
Short Answer
As mentioned by Ben James: NO.
The full SQL query does not exist on the PHP side, because the query-with-tokens and the parameters are sent separately to the database.
Only on the database side the full query exists.
Even trying to create a function to replace tokens on the PHP side would not guarantee the replacement process is the same as the SQL one (tricky stuff like token-type, bindValue vs bindParam, ...)
Workaround
This is where I elaborate on Kailash Badu's answer.
By logging all SQL queries, we can see what is really run on the server.
With mySQL, this can be done by updating the my.cnf (or my.ini in my case with Wamp server), and adding a line like:
log=[REPLACE_BY_PATH]/[REPLACE_BY_FILE_NAME]
Just do not run this in production!!!
LinkButton
component - a solution for React Router v4First, a note about many other answers to this question.
<button>
and <a>
is not valid html. ??Any answer here which suggests nesting a html button
in a React Router Link
component (or vice-versa) will render in a web browser, but it is not semantic, accessible, or valid html:
<a stuff-here><button>label text</button></a>
<button><a stuff-here>label text</a></button>
?Click to validate this markup with validator.w3.org ?
This can lead to layout/styling issues as buttons are not typically placed inside links.
<button>
tag with React Router <Link>
component.If you only want an html button
tag…
<button>label text</button>
…then, here's the right way to get a button that works like React Router’s Link
component…
Use React Router’s withRouter HOC to pass these props to your component:
history
location
match
staticContext
LinkButton
componentHere’s a LinkButton
component for you to copy/pasta:
// file: /components/LinkButton.jsx
import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router'
const LinkButton = (props) => {
const {
history,
location,
match,
staticContext,
to,
onClick,
// ? filtering out props that `button` doesn’t know what to do with.
...rest
} = props
return (
<button
{...rest} // `children` is just another prop!
onClick={(event) => {
onClick && onClick(event)
history.push(to)
}}
/>
)
}
LinkButton.propTypes = {
to: PropTypes.string.isRequired,
children: PropTypes.node.isRequired
}
export default withRouter(LinkButton)
Then import the component:
import LinkButton from '/components/LinkButton'
Use the component:
<LinkButton to='/path/to/page'>Push My Buttons!</LinkButton>
If you need an onClick method:
<LinkButton
to='/path/to/page'
onClick={(event) => {
console.log('custom event here!', event)
}}
>Push My Buttons!</LinkButton>
Update: If you're looking for another fun option made available after the above was written, check out this useRouter hook.
JavaScript can only close a window that was opened using JavaScript. Example below:
<script>
function myFunction() {
var str = "Sample";
var result = str.link("https://sample.com");
document.getElementById("demo").innerHTML = result;
}
</script>
For me I was getting the problem when deploying a geoserver WAR
into tomcat 7
To fix it, I was on Java 7 and upgrading to Java 8.
This is running under a docker container. Tomcat 7.0.75
+ Java 8
+ Geos 2.10.2
Brief answer to your question: No. You shouldn't call ConfigureAwait(false)
at the application level like that.
TL;DR version of the long answer: If you are writing a library where you don't know your consumer and don't need a synchronization context (which you shouldn't in a library I believe), you should always use ConfigureAwait(false)
. Otherwise, the consumers of your library may face deadlocks by consuming your asynchronous methods in a blocking fashion. This depends on the situation.
Here is a bit more detailed explanation on the importance of ConfigureAwait
method (a quote from my blog post):
When you are awaiting on a method with await keyword, compiler generates bunch of code in behalf of you. One of the purposes of this action is to handle synchronization with the UI (or main) thread. The key component of this feature is the
SynchronizationContext.Current
which gets the synchronization context for the current thread.SynchronizationContext.Current
is populated depending on the environment you are in. TheGetAwaiter
method of Task looks up forSynchronizationContext.Current
. If current synchronization context is not null, the continuation that gets passed to that awaiter will get posted back to that synchronization context.When consuming a method, which uses the new asynchronous language features, in a blocking fashion, you will end up with a deadlock if you have an available SynchronizationContext. When you are consuming such methods in a blocking fashion (waiting on the Task with Wait method or taking the result directly from the Result property of the Task), you will block the main thread at the same time. When eventually the Task completes inside that method in the threadpool, it is going to invoke the continuation to post back to the main thread because
SynchronizationContext.Current
is available and captured. But there is a problem here: the UI thread is blocked and you have a deadlock!
Also, here are two great articles for you which are exactly for your question:
Finally, there is a great short video from Lucian Wischik exactly on this topic: Async library methods should consider using Task.ConfigureAwait(false).
Hope this helps.
For Python 3.5+ use:
import importlib.util
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.MyClass()
For Python 3.3 and 3.4 use:
from importlib.machinery import SourceFileLoader
foo = SourceFileLoader("module.name", "/path/to/file.py").load_module()
foo.MyClass()
(Although this has been deprecated in Python 3.4.)
For Python 2 use:
import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()
There are equivalent convenience functions for compiled Python files and DLLs.
See also http://bugs.python.org/issue21436.
People don't see the nice cool Stream producers all over the Java libs.
public static double[] list(){
return new Random().ints().asDoubleStream().toArray();
}
.imgContainer {
overflow: hidden;
width: 200px;
height: 100px;
}
.imgContainer img {
width: 200px;
height: 120px;
}
<div class="imgContainer">
<img src="imageSrc" />
</div>
The containing div with essentially crop the image by hiding the overflow.
Yes and you can do so with formatting rules specified by the currently-imbued locale:
#include <iostream>
#include <iterator>
#include <string>
class timefmt
{
public:
timefmt(std::string fmt)
: format(fmt) { }
friend std::ostream& operator <<(std::ostream &, timefmt const &);
private:
std::string format;
};
std::ostream& operator <<(std::ostream& os, timefmt const& mt)
{
std::ostream::sentry s(os);
if (s)
{
std::time_t t = std::time(0);
std::tm const* tm = std::localtime(&t);
std::ostreambuf_iterator<char> out(os);
std::use_facet<std::time_put<char>>(os.getloc())
.put(out, os, os.fill(),
tm, &mt.format[0], &mt.format[0] + mt.format.size());
}
os.width(0);
return os;
}
int main()
{
std::cout << timefmt("%c");
}
Output:
Fri Sep 6 20:33:31 2013
Since all these tools lack a validation function their outcomes are just drawings and no better tool for creating nice drawings is a piece of paper and pen. Afterwards you can scan your diagrams and insert them into your team's wiki.
Add this to onCreate
// Getting application context
Context context = getActivity();
Private Function LoaderData(ByVal strSql As String) As DataTable
Dim cnn As SqlConnection
Dim dad As SqlDataAdapter
Dim dtb As New DataTable
cnn = New SqlConnection(My.Settings.mySqlConnectionString)
Try
cnn.Open()
dad = New SqlDataAdapter(strSql, cnn)
dad.Fill(dtb)
cnn.Close()
dad.Dispose()
Catch ex As Exception
cnn.Close()
MsgBox(ex.Message)
End Try
Return dtb
End Function
In many cases an element must be positioned for z-index
to work.
Indeed, applying position: relative
to the elements in the question would likely solve the problem (but there's not enough code provided to know for sure).
Actually, position: fixed
, position: absolute
and position: sticky
will also enable z-index
, but those values also change the layout. With position: relative
the layout isn't disturbed.
Essentially, as long as the element isn't position: static
(the default setting) it is considered positioned and z-index
will work.
Many answers to "Why isn't z-index working?" questions assert that z-index
only works on positioned elements. As of CSS3, this is no longer true.
Elements that are flex items or grid items can use z-index
even when position
is static
.
From the specs:
Flex items paint exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and
z-index
values other thanauto
create a stacking context even ifposition
isstatic
.5.4. Z-axis Ordering: the
z-index
propertyThe painting order of grid items is exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and
z-index
values other thanauto
create a stacking context even ifposition
isstatic
.
Here's a demonstration of z-index
working on non-positioned flex items: https://jsfiddle.net/m0wddwxs/
None of the answers so far offer a complete solution. There are quite a few issues to address:
keydown
and keypress
handlers (e.g. backspace and delete keys are suppressed by some browsers).keydown
is not a good idea. There are situations where a keydown does NOT result in a keypress!setTimeout()
style solutions get delayed under Google Chrome/Blink web browsers until the user stops typing.A more correct solution will handle the keypress
, keyup
, input
, and change
events.
Example:
<p><input id="editvalue" type="text"></p>
<p>The text box contains: <span id="labelvalue"></span></p>
<script>
function UpdateDisplay()
{
var inputelem = document.getElementById("editvalue");
var s = inputelem.value;
var labelelem = document.getElementById("labelvalue");
labelelem.innerText = s;
}
// Initial update.
UpdateDisplay();
// Register event handlers.
var inputelem = document.getElementById("editvalue");
inputelem.addEventListener('keypress', UpdateDisplay);
inputelem.addEventListener('keyup', UpdateDisplay);
inputelem.addEventListener('input', UpdateDisplay);
inputelem.addEventListener('change', UpdateDisplay);
</script>
Fiddle:
http://jsfiddle.net/VDd6C/2175/
Handling all four events catches all of the edge cases. When working with input from a user, all types of input methods should be considered and cross-browser and cross-device functionality should be verified. The above code has been tested in Firefox, Edge, and Chrome on desktop as well as the mobile devices I own.
See A comparison of the C++ casting operators.
However, using the same syntax for a variety of different casting operations can make the intent of the programmer unclear.
Furthermore, it can be difficult to find a specific type of cast in a large codebase.
the generality of the C-style cast can be overkill for situations where all that is needed is a simple conversion. The ability to select between several different casting operators of differing degrees of power can prevent programmers from inadvertently casting to an incorrect type.
I had the same problem after setting up my environment on Windows 10. I have Python 3.6.2 x64 installed as my default Python distribution and is in my PATH so I can launch from cmd prompt.
I installed PyQt5 (pip install pyqt5
) and Spyder (pip install spyder
) which both installed w/out error and included all of the necessary dependencies.
To launch Spyder, I created a simple Python script (Spyder.py):
# Spyder Start Script
from spyder.app import start
start.main()
Then I created a Windows batch file (Spyder.bat):
@echo off
python c:\<path_to_Spyder_py>\Spyder.py
Lastly, I created a shortcut on my desktop which launches Spyder.bat and updated the icon to one I downloaded from the Spyder github project.
Works like a charm for me.
You could use an onclick
event handler in order to get the input value for the text field. Make sure you give the field an unique id
attribute so you can refer to it safely through document.getElementById()
:
If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">
. Create new elements by means of document.createElement()
, and use appendChild()
to append each of them to the container. You might be interested in outputting a meaningful name
attribute (e.g. name="member"+i
for each of the dynamically generated <input>
s if they are to be submitted in a form.
Notice you could also create <br/>
elements with document.createElement('br')
. If you want to just output some text, you can use document.createTextNode()
instead.
Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes()
and removeChild()
together.
<html>
<head>
<script type='text/javascript'>
function addFields(){
// Number of inputs to create
var number = document.getElementById("member").value;
// Container <div> where dynamic content will be placed
var container = document.getElementById("container");
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
// Append a node with a random text
container.appendChild(document.createTextNode("Member " + (i+1)));
// Create an <input> element, set its type and name attributes
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
}
</script>
</head>
<body>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
<a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
<div id="container"/>
</body>
</html>
_x000D_
See a working sample in this JSFiddle.
I think the exception safety part of mr mpark's answer is still a valid concern. when creating a shared_ptr like this: shared_ptr< T >(new T), the new T may succeed, while the shared_ptr's allocation of control block may fail. in this scenario, the newly allocated T will leak, since the shared_ptr has no way of knowing that it was created in-place and it is safe to delete it. or am I missing something? I don't think the stricter rules on function parameter evaluation help in any way here...
The T
doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.
The Z
stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).
Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime()
method. You could have used Q
or M
or Monty Python
and the method would have returned them unchanged as well; the method only looks for patterns starting with %
to replace those with information from the datetime
object.
As Ben said, you are POSTing your request ( HttpMethod.Post specified in your code )
The querystring (get) parameters included in your url probably will not do anything.
Try this:
string url = "http://myserver/method";
string content = "param1=1¶m2=2";
HttpClientHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage response = await httpClient.SendAsync(request,content);
HTH,
bovako
You can also try out ctrl + alt + I even though you can also use l as well.
I find the most simple is
shell "explorer.exe URL"
This also works to open local folders.
See this example: http://www.p2e.dk/diverse/detectPaste.htm
It essentialy tracks every change with oninput event and then checks if it’s a paste by string comparison. Oh, and in IE there’s an onpaste event. So:
$ (something).bind ("input paste", function (e) {
// check for paste as in example above and
// do something
})
In order to read a csv in that doesn't have a header and for only certain columns you need to pass params header=None
and usecols=[3,6]
for the 4th and 7th columns:
df = pd.read_csv(file_path, header=None, usecols=[3,6])
See the docs
Simply do it
sudo apt install php-mysqli
It works perfectly and it is version independent
Use This [Tested]
To get numeric
SELECT column1
FROM table
WHERE Isnumeric(column1) = 1; // will return Numeric values
To get non-numeric
SELECT column1
FROM table
WHERE Isnumeric(column1) = 0; // will return non-numeric values
You cannot. The column order is just a "cosmetic" thing we humans care about - to SQL Server, it's almost always absolutely irrelevant.
What SQL Server Management Studio does in the background when you change column order there is recreating the table from scratch with a new CREATE TABLE
command, copying over the data from the old table, and then dropping it.
There is no SQL command to define the column ordering.
You can use window.opener, window.parent, or window.top to reference the window in question. From there, you just call the reload
method (e.g.: window.parent.location.reload()
).
However, as a caveat, you might have problems with window.opener
if you need to navigate away from the originally opened page since the reference will be lost.
Nothing can be worse than infinity.
Activity 1 uses startActivityForResult:
startActivityForResult(ActivityTwo, ActivityTwoRequestCode);
Activity 2 is launched and you can perform the operation, to close the Activity do this:
Intent output = new Intent();
output.putExtra(ActivityOne.Number1Code, num1);
output.putExtra(ActivityOne.Number2Code, num2);
setResult(RESULT_OK, output);
finish();
Activity 1 - returning from the previous activity will call onActivityResult:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ActivityTwoRequestCode && resultCode == RESULT_OK && data != null) {
num1 = data.getIntExtra(Number1Code);
num2 = data.getIntExtra(Number2Code);
}
}
UPDATE: Answer to Seenu69's comment, In activity two,
int result = Integer.parse(EditText1.getText().toString())
+ Integer.parse(EditText2.getText().toString());
output.putExtra(ActivityOne.KEY_RESULT, result);
Then in activity one,
int result = data.getExtra(KEY_RESULT);
uses-permission android:name="android.permission.SEND_SMS"/>
Prem
at this thread ) and replace the below phone_Number by an actual number, it will work:startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", "phone_Number", null)));
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_now
"NOW() returns a constant time that indicates the time at which the statement began to execute. (Within a stored routine or trigger, NOW() returns the time at which the routine or triggering statement began to execute.) This differs from the behavior for SYSDATE(), which returns the exact time at which it executes as of MySQL 5.0.13. "
Another option is to get a ".pem" (public key) file for that particular server, and install it locally into the heart of your JRE's "cacerts" file (use the keytool helper application), then it will be able to download from that server without complaint, without compromising the entire SSL structure of your running JVM and enabling download from other unknown cert servers...
Personally i think you should learn the hard way first. It will make you a better programmer and you will be able to solve that one of a kind issue when it comes up. After you can do it with pure JavaScript then using jQuery to speed up development is just an added bonus.
If you can do it the hard way then you can do it the easy way, it doesn't work the other way around. That applies to any programming paradigm.
In view.py Implement function like,
def download(request, id):
obj = your_model_name.objects.get(id=id)
filename = obj.model_attribute_name.path
response = FileResponse(open(filename, 'rb'))
return response
On the tab:
You can access all derived data and clear by deleting them.
For ng-click working properly you need define your controller after angularjs script binding and use it via $scope.
These posts apparently are in the wrong order! This is #1 in a series of 3 posts. Sorry.
In attempting to use Lie Ryan's code, I had problems retrieving stored information. The vector's elements are not stored contiguously,as you can see by "cheating" a bit and storing the pointer to each element's address (which of course defeats the purpose of the dynamic array concept) and examining them.
With a bit of tinkering, via:
ss_vector* vector; // pull this out to be a global vector
// Then add the following to attempt to recover stored values.
int return_id_value(int i,apple* aa) // given ptr to component,return data item
{ printf("showing apple[%i].id = %i and other_id=%i\n",i,aa->id,aa->other_id);
return(aa->id);
}
int Test(void) // Used to be "main" in the example
{ apple* aa[10]; // stored array element addresses
vector = ss_init_vector(sizeof(apple));
// inserting some items
for (int i = 0; i < 10; i++)
{ aa[i]=init_apple(i);
printf("apple id=%i and other_id=%i\n",aa[i]->id,aa[i]->other_id);
ss_vector_append(vector, aa[i]);
}
// report the number of components
printf("nmbr of components in vector = %i\n",(int)vector->size);
printf(".*.*array access.*.component[5] = %i\n",return_id_value(5,aa[5]));
printf("components of size %i\n",(int)sizeof(apple));
printf("\n....pointer initial access...component[0] = %i\n",return_id_value(0,(apple *)&vector[0]));
//.............etc..., followed by
for (int i = 0; i < 10; i++)
{ printf("apple[%i].id = %i at address %i, delta=%i\n",i, return_id_value(i,aa[i]) ,(int)aa[i],(int)(aa[i]-aa[i+1]));
}
// don't forget to free it
ss_vector_free(vector);
return 0;
}
It's possible to access each array element without problems, as long as you know its address, so I guess I'll try adding a "next" element and use this as a linked list. Surely there are better options, though. Please advise.
You can use mysql scheduler to run it each 5 seconds. You can find samples at http://dev.mysql.com/doc/refman/5.1/en/create-event.html
Never used it but I hope this would work:
CREATE EVENT myevent
ON SCHEDULE EVERY 5 SECOND
DO
CALL delete_rows_links();
You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.
What I found out was to use the K switch like this:
start cmd /k echo Hello, World!
start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.
You can also use the /C switch for something similar.
start cmd /C pause
This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.
Use the following in your batch file:
start cmd.exe /c "more-batch-commands-here"
or
start cmd.exe /k "more-batch-commands-here"
/c Carries out the command specified by string and then terminates
/k Carries out the command specified by string but remains
The /c
and /k
options controls what happens once your command finishes running. With /c
the terminal window will close automatically, leaving your desktop clean. With /k
the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.
Consult the cmd.exe documentation using cmd /?
for more details.
The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.
Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt
Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"
Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""
Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""
Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""
Source: http://ss64.com/nt/cmd.html
The worksheet formula, =CELL("color",D3)
returns 1
if the cell is formatted with color for negative values (else returns 0
).
You can solve this with a bit of VBA. Insert this into a VBA code module:
Function CellColor(xlRange As Excel.Range)
CellColor = xlRange.Cells(1, 1).Interior.ColorIndex
End Function
Then use the function =CellColor(D3)
to display the .ColorIndex
of D3
The issue I had is that sometimes I will need to get at a value that is deeply
nested. Normally you would need to do a type assertion at each level, so I went
ahead and just made a method that takes a map[string]interface{}
and a
string
key, and returns the resulting map[string]interface{}
.
The issue that cropped up for me was that at some depths you will encounter a Slice instead of Map. So I also added methods to return a Slice from Map, and Map from Slice. I didnt do one for Slice to Slice, but you could easily add that if needed. Here are the methods:
package main
type Slice []interface{}
type Map map[string]interface{}
func (m Map) M(s string) Map {
return m[s].(map[string]interface{})
}
func (m Map) A(s string) Slice {
return m[s].([]interface{})
}
func (a Slice) M(n int) Map {
return a[n].(map[string]interface{})
}
and example code:
package main
import (
"encoding/json"
"fmt"
"log"
"os"
)
func main() {
o, e := os.Open("a.json")
if e != nil {
log.Fatal(e)
}
in_m := Map{}
json.NewDecoder(o).Decode(&in_m)
out_m := in_m.
M("contents").
M("sectionListRenderer").
A("contents").
M(0).
M("musicShelfRenderer").
A("contents").
M(0).
M("musicResponsiveListItemRenderer").
M("navigationEndpoint").
M("browseEndpoint")
fmt.Println(out_m)
}
repositories {
mavenCentral()
}
I added this in build.gradle, and it worked.
To get a definitive reason, you'd need to ask the designer(s) of that API.
But one possible reason is that the intent of a (hypothetical) nextChar
would not fit into the scanning model very well.
If nextChar()
to behaved like read()
on a Reader
and simply returned the next unconsumed character from the scanner, then it is behaving inconsistently with the other next<Type>
methods. These skip over delimiter characters before they attempt to parse a value.
If nextChar()
to behaved like (say) nextInt
then:
the delimiter skipping would be "unexpected" for some folks, and
there is the issue of whether it should accept a single "raw" character, or a sequence of digits that are the numeric representation of a char
, or maybe even support escaping or something1.
No matter what choice they made, some people wouldn't be happy. My guess is that the designers decided to stay away from the tarpit.
1 - Would vote strongly for the raw character approach ... but the point is that there are alternatives that need to be analysed, etc.
Depends on what product you're using, but most support something like
SELECT IFNULL(MAX(X), 0, MAX(X)) AS MaxX FROM tbl WHERE XID = 1
or
SELECT CASE MAX(X) WHEN NULL THEN 0 ELSE MAX(X) FROM tbl WHERE XID = 1
String#strip
- remove all whitespace from the start and the end.
String#lstrip
- just from the start.
String#rstrip
- just from the end.
String#chomp
(with no arguments) - deletes line separators (\n
or \r\n
) from the end.
String#chop
- deletes the last character.
String#delete
- x.delete(" \t\r\n")
- deletes all listed whitespace.
String#gsub
- x.gsub(/[[:space:]]/, '')
- removes all whitespace, including unicode ones.
Note: All the methods above return a new string instead of mutating the original. If you want to change the string in place, call the corresponding method with !
at the end.
You could use:
NSString *stringWithoutSpaces = [myString
stringByReplacingOccurrencesOfString:@" " withString:@""];
On Android prior to 4.2, go to Google Settings, tap Verify apps and uncheck the option Verify apps.
On Android 4.2+, uncheck the option Settings > Security > Verify apps and/or Settings > Developer options > Verify apps over USB.
Python3:
import importlib.machinery
loader = importlib.machinery.SourceFileLoader('report', '/full/path/report/other_py_file.py')
handle = loader.load_module('report')
handle.mainFunction(parameter)
This method can be used to import whichever way you want in a folder structure (backwards, forwards doesn't really matter, i use absolute paths just to be sure).
There's also the more normal way of importing a python module in Python3,
import importlib
module = importlib.load_module('folder.filename')
module.function()
Kudos to Sebastian for spplying a similar answer for Python2:
import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()
class LL(object):
def __init__(self,val):
self.val = val
self.next = None
def pushNodeEnd(self,top,val):
if top is None:
top.val=val
top.next=None
else:
tmp=top
while (tmp.next != None):
tmp=tmp.next
newNode=LL(val)
newNode.next=None
tmp.next=newNode
def pushNodeFront(self,top,val):
if top is None:
top.val=val
top.next=None
else:
newNode=LL(val)
newNode.next=top
top=newNode
def popNodeFront(self,top):
if top is None:
return
else:
sav=top
top=top.next
return sav
def popNodeEnd(self,top):
if top is None:
return
else:
tmp=top
while (tmp.next != None):
prev=tmp
tmp=tmp.next
prev.next=None
return tmp
top=LL(10)
top.pushNodeEnd(top, 20)
top.pushNodeEnd(top, 30)
pop=top.popNodeEnd(top)
print (pop.val)
If you want it cross-browser, your best bet is to do it on the server. You could have an API that takes a file URL and returns you the EXIF data; PHP has a module for that.
This could be done using Ajax so it would be seamless to the user. If you don't care about cross-browser compatibility, and can rely on HTML5 file functionality, look into the library JsJPEGmeta that will allow you to get that data in native JavaScript.
Visual Studio Community is same (almost) as professional edition. What differs is that VS community do not have TFS features, and the licensing is different. As stated by @Stefan.
The different versions on VS are compared here - https://www.visualstudio.com/en-us/products/compare-visual-studio-2015-products-vs
I wrote this piece of code for object comparison, and it seems to work. check the assertions:
function countProps(obj) {
var count = 0;
for (k in obj) {
if (obj.hasOwnProperty(k)) {
count++;
}
}
return count;
};
function objectEquals(v1, v2) {
if (typeof(v1) !== typeof(v2)) {
return false;
}
if (typeof(v1) === "function") {
return v1.toString() === v2.toString();
}
if (v1 instanceof Object && v2 instanceof Object) {
if (countProps(v1) !== countProps(v2)) {
return false;
}
var r = true;
for (k in v1) {
r = objectEquals(v1[k], v2[k]);
if (!r) {
return false;
}
}
return true;
} else {
return v1 === v2;
}
}
assert.isTrue(objectEquals(null,null));
assert.isFalse(objectEquals(null,undefined));
assert.isTrue(objectEquals("hi","hi"));
assert.isTrue(objectEquals(5,5));
assert.isFalse(objectEquals(5,10));
assert.isTrue(objectEquals([],[]));
assert.isTrue(objectEquals([1,2],[1,2]));
assert.isFalse(objectEquals([1,2],[2,1]));
assert.isFalse(objectEquals([1,2],[1,2,3]));
assert.isTrue(objectEquals({},{}));
assert.isTrue(objectEquals({a:1,b:2},{a:1,b:2}));
assert.isTrue(objectEquals({a:1,b:2},{b:2,a:1}));
assert.isFalse(objectEquals({a:1,b:2},{a:1,b:3}));
assert.isTrue(objectEquals({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}},{1:{name:"mhc",age:28}, 2:{name:"arb",age:26}}));
assert.isFalse(objectEquals({1:{name:"mhc",age:28}, 2:{name:"arb",age:26}},{1:{name:"mhc",age:28}, 2:{name:"arb",age:27}}));
assert.isTrue(objectEquals(function(x){return x;},function(x){return x;}));
assert.isFalse(objectEquals(function(x){return x;},function(y){return y+2;}));
Unsorted vector:
if (std::find(v.begin(), v.end(),value)!=v.end())
...
Sorted vector:
if (std::binary_search(v.begin(), v.end(), value)
...
P.S. may need to include <algorithm>
header
There is a better way that is safer and will not slow down your application. How Excel is set up, a cell can have either a value or a formula; the formula can not refer to its own cell. You end up with an infinite loop, since the new value would cause another calculation... . Use a helper column to calculate the value based on what you put in the other cell. For Example:
Column A is a True or False, Column B contains a monetary value, Column C contains the folowing formula: =B1
Now, to calculate that column B will be highlighted yellow in a conditional format only if Column A is True and Column B is greater than Zero...
=AND(A1=True,C1>0)
You can then choose to hide column C
To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
What you tried was df['V1','V2']
this will raise a KeyError
as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]]
.
import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()
The issue in my case was I included a constructor taking parameters but not an empty constructor with the Inject annotation, like so.
@Inject public VisitorBean() {}
I just tested it without any constructor and this appears to work also.
Years after everyone's answer, I too want to present how I did it for my project
/// <summary>
/// /Reads an excel file and converts it into dataset with each sheet as each table of the dataset
/// </summary>
/// <param name="filename"></param>
/// <param name="headers">If set to true the first row will be considered as headers</param>
/// <returns></returns>
public DataSet Import(string filename, bool headers = true)
{
var _xl = new Excel.Application();
var wb = _xl.Workbooks.Open(filename);
var sheets = wb.Sheets;
DataSet dataSet = null;
if (sheets != null && sheets.Count != 0)
{
dataSet = new DataSet();
foreach (var item in sheets)
{
var sheet = (Excel.Worksheet)item;
DataTable dt = null;
if (sheet != null)
{
dt = new DataTable();
var ColumnCount = ((Excel.Range)sheet.UsedRange.Rows[1, Type.Missing]).Columns.Count;
var rowCount = ((Excel.Range)sheet.UsedRange.Columns[1, Type.Missing]).Rows.Count;
for (int j = 0; j < ColumnCount; j++)
{
var cell = (Excel.Range)sheet.Cells[1, j + 1];
var column = new DataColumn(headers ? cell.Value : string.Empty);
dt.Columns.Add(column);
}
for (int i = 0; i < rowCount; i++)
{
var r = dt.NewRow();
for (int j = 0; j < ColumnCount; j++)
{
var cell = (Excel.Range)sheet.Cells[i + 1 + (headers ? 1 : 0), j + 1];
r[j] = cell.Value;
}
dt.Rows.Add(r);
}
}
dataSet.Tables.Add(dt);
}
}
_xl.Quit();
return dataSet;
}
You append a newline to both the username and the password, i.e. the output would be something like
Sebastian
password
John
hfsjaijn
use fwrite($fh,$user." ".$password."\n");
instead to have them both on one line.
Or use fputcsv() to write the data and fgetcsv()
to fetch it. This way you would at least avoid encoding problems like e.g. with $username='Charles, III';
...i.e. setting aside all the things that are wrong about storing plain passwords in plain files and using _GET for this type of operation (use _POST instead) ;-)
After writing
header('HTTP/1.0 404 Not Found');
add one more header for any inexisting page on your site. It works, for sure.
header("Location: http://yoursite/nowhere");
die;
With RxJS
:
import { timer } from 'rxjs';
// ...
timer(your_delay_in_ms).subscribe(x => { your_action_code_here })
x
is 0.
If you give a second argument period
to timer
, a new number will be emitted each period
milliseconds (x = 0 then x = 1, x = 2, ...).
See the official doc for more details.
You may need to give boolean arg in your calls, e.g. use ax.yaxis.grid(True)
instead of ax.yaxis.grid()
. Additionally, since you are using both of them you can combine into ax.grid
, which works on both, rather than doing it once for each dimension.
ax = plt.gca()
ax.grid(True)
That should sort you out.
I am a beginner tinkering on somebody else's code so please be lenient and further correct my errors. I tried your code and played with the VBA help The following worked with me:
Function currAddressTest(dataRangeTest As Range) As String
currAddressTest = ActiveSheet.Name & "$" & dataRangeTest.Address(False, False)
End Function
When I select data source argument for my function, it is turned into Sheet1$A1:G3 format. If excel changes it to Table1[#All] reference in my formula, the function still works properly
I then used it in your function (tried to play and add another argument to be injected to WHERE...
Function SQL(dataRange As Range, CritA As String)
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim currAddress As String
currAddress = ActiveSheet.Name & "$" & dataRange.Address(False, False)
strFile = ThisWorkbook.FullName
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
strSQL = "SELECT * FROM [" & currAddress & "]" & _
"WHERE [A] = '" & CritA & "' " & _
"ORDER BY 1 ASC"
rs.Open strSQL, cn
SQL = rs.GetString
End Function
Hope your function develops further, I find it very useful. Have a nice day!
You can mount a folder as a drive. From the command line, if you have a path C:\path\to\long\folder
you can map it to drive letter X:
using:
subst x: \path\to\long\folder
Underscore has few methods to do this;
1. _.extend(destination, *sources)
Copy all of the properties in the source objects over to the destination object, and return the destination object.
_.extend(a, _.extend(b, c));
=> {"one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }
Or
_.extend(a, b);
=> {"one" : 1, "two" : 2, "three" : 3}
_.extend(a, c);
=> {"one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }
2. _.defaults(object, *defaults)
Fill in undefined properties in object with values from the defaults objects, and return the object.
_.defaults(a, _.defaults(b, c));
=> {"one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }
Or
_.defaults(a, b);
=> {"one" : 1, "two" : 2, "three" : 3}
_.defaults(a, c);
=> {"one" : 1, "two" : 2, "three" : 3, "four" : 4, "five" : 5 }
I would say that J2EE experience = in-depth experience with a few J2EE technologies, general knowledge about most J2EE technologies, and general experience with enterprise software in general.
Best worked for me is inscripts .
https://github.com/weblyzard/inscriptis
import urllib.request
from inscriptis import get_text
url = "http://www.informationscience.ch"
html = urllib.request.urlopen(url).read().decode('utf-8')
text = get_text(html)
print(text)
The results are really good
I think what you actually want is:
git checkout -B mergeBranch branchB
git merge -s ours branchA
git checkout branchA
git merge mergeBranch
git branch -D mergeBranch
This seems clumsy, but it should work. The only think I really dislike about this solution is the git history will be confusing... But at least the history will be completely preserved and you won't need to do something special for deleted files.
The method you want is BigInteger#valueOf(long val).
E.g.,
BigInteger bi = BigInteger.valueOf(myInteger.intValue());
Making a String first is unnecessary and undesired.
There is no easy way to remove the "outdated" stuff from an existing workspace. Using the "clean" parameter will not really help, as many of the files you refer to are "free form data", only known to the plugins that are no longer available.
Your best bet is to optimize the re-import, where I would like to point out the following:
${old_workspace}/.metadata/.plugins/org.eclipse.core.runtime/.settings
folder from the old to the new workspace. This is surely the fastest way, but it may lead to weird behaviour, because some of your plugins may depend on these settings and on some of the mentioned "free form data" stored elsewhere. (There are even people symlinking these folders over multiple workspaces, but this really requires to use the same plugins on all workspaces.)I think this code show the procedure more clear.
<?php
$a = array ('zero','one','two', 'three');
foreach ($a as &$v) {
}
var_dump($a);
foreach ($a as $v) {
var_dump($a);
}
Result: (Take attention on the last two array)
array(4) {
[0]=>
string(4) "zero"
[1]=>
string(3) "one"
[2]=>
string(3) "two"
[3]=>
&string(5) "three"
}
array(4) {
[0]=>
string(4) "zero"
[1]=>
string(3) "one"
[2]=>
string(3) "two"
[3]=>
&string(4) "zero"
}
array(4) {
[0]=>
string(4) "zero"
[1]=>
string(3) "one"
[2]=>
string(3) "two"
[3]=>
&string(3) "one"
}
array(4) {
[0]=>
string(4) "zero"
[1]=>
string(3) "one"
[2]=>
string(3) "two"
[3]=>
&string(3) "two"
}
array(4) {
[0]=>
string(4) "zero"
[1]=>
string(3) "one"
[2]=>
string(3) "two"
[3]=>
&string(3) "two"
}
Is because by the way python is designed the alternatives would hardly work. Python is designed to allow methods or functions to be defined in a context where both implicit this
(a-la Java/C++) or explicit @
(a-la ruby) wouldn't work. Let's have an example with the explicit approach with python conventions:
def fubar(x):
self.x = x
class C:
frob = fubar
Now the fubar
function wouldn't work since it would assume that self
is a global variable (and in frob
as well). The alternative would be to execute method's with a replaced global scope (where self
is the object).
The implicit approach would be
def fubar(x)
myX = x
class C:
frob = fubar
This would mean that myX
would be interpreted as a local variable in fubar
(and in frob
as well). The alternative here would be to execute methods with a replaced local scope which is retained between calls, but that would remove the posibility of method local variables.
However the current situation works out well:
def fubar(self, x)
self.x = x
class C:
frob = fubar
here when called as a method frob
will receive the object on which it's called via the self
parameter, and fubar
can still be called with an object as parameter and work the same (it is the same as C.frob
I think).
You can use the multiprocessing module. For this case I might use a processing pool:
from multiprocessing import Pool
pool = Pool()
result1 = pool.apply_async(solve1, [A]) # evaluate "solve1(A)" asynchronously
result2 = pool.apply_async(solve2, [B]) # evaluate "solve2(B)" asynchronously
answer1 = result1.get(timeout=10)
answer2 = result2.get(timeout=10)
This will spawn processes that can do generic work for you. Since we did not pass processes
, it will spawn one process for each CPU core on your machine. Each CPU core can execute one process simultaneously.
If you want to map a list to a single function you would do this:
args = [A, B]
results = pool.map(solve1, args)
Don't use threads because the GIL locks any operations on python objects.
It's the other way around: =
and ==
are for string comparisons, -eq
is for numeric ones. -eq
is in the same family as -lt
, -le
, -gt
, -ge
, and -ne
, if that helps you remember which is which.
==
is a bash-ism, by the way. It's better to use the POSIX =
. In bash the two are equivalent, and in plain sh =
is the only one guaranteed to work.
$ a=foo
$ [ "$a" = foo ]; echo "$?" # POSIX sh
0
$ [ "$a" == foo ]; echo "$?" # bash specific
0
$ [ "$a" -eq foo ]; echo "$?" # wrong
-bash: [: foo: integer expression expected
2
(Side note: Quote those variable expansions! Do not leave out the double quotes above.)
If you're writing a #!/bin/bash
script then I recommend using [[
instead. The doubled form has more features, more natural syntax, and fewer gotchas that will trip you up. Double quotes are no longer required around $a
, for one:
$ [[ $a == foo ]]; echo "$?" # bash specific
0
See also:
If you really need the functionality for some reason and want it to be cross-browser compatible and not worry for strict stuff and be forward compatible then pass a this reference:
function main()
{
Hello(this);
}
function Hello(caller)
{
// caller will be the object that called Hello. boom like that...
// you can add an undefined check code if the function Hello
// will be called without parameters from somewhere else
}
It's work for Iphone
<?php
$browser = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
if ($browser == true){
$browser = 'iphone';
}
?>
Generally you have'got an answer now but maybe my class I created will be also helpfull. For me it solves all my requirements I have ever had in my Pyhon projects.
class GetDate:
def __init__(self, date, format="%Y-%m-%d"):
self.tz = pytz.timezone("Europe/Warsaw")
if isinstance(date, str):
date = datetime.strptime(date, format)
self.date = date.astimezone(self.tz)
def time_delta_days(self, days):
return self.date + timedelta(days=days)
def time_delta_hours(self, hours):
return self.date + timedelta(hours=hours)
def time_delta_seconds(self, seconds):
return self.date + timedelta(seconds=seconds)
def get_minimum_time(self):
return datetime.combine(self.date, time.min).astimezone(self.tz)
def get_maximum_time(self):
return datetime.combine(self.date, time.max).astimezone(self.tz)
def get_month_first_day(self):
return datetime(self.date.year, self.date.month, 1).astimezone(self.tz)
def current(self):
return self.date
def get_month_last_day(self):
lastDay = calendar.monthrange(self.date.year, self.date.month)[1]
date = datetime(self.date.year, self.date.month, lastDay)
return datetime.combine(date, time.max).astimezone(self.tz)
How to use it
self.tz = pytz.timezone("Europe/Warsaw")
- here you define Time Zone you want to use in projectGetDate("2019-08-08").current()
- this will convert your string date to time aware object with timezone you defined in pt 1. Default string format is format="%Y-%m-%d"
but feel free to change it. (eg. GetDate("2019-08-08 08:45", format="%Y-%m-%d %H:%M").current()
)GetDate("2019-08-08").get_month_first_day()
returns given date (string or object) month first dayGetDate("2019-08-08").get_month_last_day()
returns given date month last dayGetDate("2019-08-08").minimum_time()
returns given date day startGetDate("2019-08-08").maximum_time()
returns given date day endGetDate("2019-08-08").time_delta_days({number_of_days})
returns given date + add {number of days} (you can also call: GetDate(timezone.now()).time_delta_days(-1)
for yesterday)GetDate("2019-08-08").time_delta_haours({number_of_hours})
similar to pt 7 but working on hoursGetDate("2019-08-08").time_delta_seconds({number_of_seconds})
similar to pt 7 but working on secondsIt is simple! You create new timer.
Timer timer = new Timer();
Then you extend the timer task
class UpdateBallTask extends TimerTask {
Ball myBall;
public void run() {
//calculate the new position of myBall
}
}
And then add the new task to the Timer with some update interval
final int FPS = 40;
TimerTask updateBall = new UpdateBallTask();
timer.scheduleAtFixedRate(updateBall, 0, 1000/FPS);
Disclaimer: This is not the ideal solution. This is solution using the Timer class (as asked by OP). In Android SDK, it is recommended to use the Handler class (there is example in the accepted answer).
You have to add the jar/war of the module B in the module A and add the classpath in your new spring-module file. Just add this line
spring-moduleA.xml - is a file in module A under the resource folder. By adding this line, it imports all the bean definition from module A to module B.
MODULE B/ spring-moduleB.xml
import resource="classpath:spring-moduleA.xml"/>
<bean id="helloBeanB" class="basic.HelloWorldB">
<property name="name" value="BMVNPrj" />
</bean>
Perhaps with the canvas tag (though it's not portable). There's a blog about how to rotate an image with canvas here, I suppose if you can rotate it, you can resize it. Maybe it can be a starting point.
See this library also.
Type the following in the linux/ubuntu terminal
crontab -e
select an editor (sometime it asks for the editor) and this to run for every minute
* * * * * /usr/bin/php path/to/cron.php &> /dev/null
You can substitue a function pointer with an interface. Lets say you want to run through a collection and do something with each element.
public interface IFunction {
public void execute(Object o);
}
This is the interface we could pass to some say CollectionUtils2.doFunc(Collection c, IFunction f).
public static void doFunc(Collection c, IFunction f) {
for (Object o : c) {
f.execute(o);
}
}
As an example say we have a collection of numbers and you would like to add 1 to every element.
CollectionUtils2.doFunc(List numbers, new IFunction() {
public void execute(Object o) {
Integer anInt = (Integer) o;
anInt++;
}
});
You can use the below code to change the button to Left side.
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.zakasoft.mymap.MapsActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|top"
android:text="Send"
android:padding="10dp"
android:layout_marginTop="20dp"
android:paddingRight="10dp"/>
</fragment>
"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."
http://www.sightspecific.com/~mosh/www_faq/multrec.html
For a quick fix to your problem, change your ;
to a comma ,
and eliminate the spaces between email addresses
<a href='mailto:[email protected],[email protected]'>Email Us</a>
First you should drop the problematic DEFAULT constraint
, after that you can drop the column
alter table tbloffers drop constraint [ConstraintName]
go
alter table tbloffers drop column checkin
But the error may appear from other reasons - for example the user defined function or view with SCHEMABINDING
option set for them.
UPD: Completely automated dropping of constraints script:
DECLARE @sql NVARCHAR(MAX)
WHILE 1=1
BEGIN
SELECT TOP 1 @sql = N'alter table tbloffers drop constraint ['+dc.NAME+N']'
from sys.default_constraints dc
JOIN sys.columns c
ON c.default_object_id = dc.object_id
WHERE
dc.parent_object_id = OBJECT_ID('tbloffers')
AND c.name = N'checkin'
IF @@ROWCOUNT = 0 BREAK
EXEC (@sql)
END
You can simply check whether the element length is undefined or not just by using
var theHref = $(obj.mainImg_select).attr('href');
if (theHref){
//get the length here if the element is not undefined
elementLength = theHref.length
// do stuff
} else {
// do other stuff
}
Replace whatever is in the address bar with this:
javascript:document.getElementById('serverTime').innerHTML='[text here]';
For your example, Dirk's answer is perfect. If you instead had a data frame and wanted to add that sort of sequence as a column, you could also use group
from groupdata2 (disclaimer: my package) to greedily divide the datapoints into groups.
# Attach groupdata2
library(groupdata2)
# Create a random data frame
df <- data.frame("x" = rnorm(27))
# Create groups with 5 members each (except last group)
group(df, n = 5, method = "greedy")
x .groups
<dbl> <fct>
1 0.891 1
2 -1.13 1
3 -0.500 1
4 -1.12 1
5 -0.0187 1
6 0.420 2
7 -0.449 2
8 0.365 2
9 0.526 2
10 0.466 2
# … with 17 more rows
There's a whole range of methods for creating this kind of grouping factor. E.g. by number of groups, a list of group sizes, or by having groups start when the value in some column differs from the value in the previous row (e.g. if a column is c("x","x","y","z","z")
the grouping factor would be c(1,1,2,3,3)
.
In my case, it was just because there were no source file in the target. All of my library was template with source code in the header. Adding an empty file.cpp solved the problem.
The FragmentManger's function add and replace can be described as these 1. add means it will add the fragment in the fragment back stack and it will show at given frame you are providing like
getFragmentManager.beginTransaction.add(R.id.contentframe,Fragment1.newInstance(),null)
2.replace means that you are replacing the fragment with another fragment at the given frame
getFragmentManager.beginTransaction.replace(R.id.contentframe,Fragment1.newInstance(),null)
The Main utility between the two is that when you are back stacking the replace will refresh the fragment but add will not refresh previous fragment.
I read all the posts here and realized that we may need a real life example. Why, actually, we have @property?
So, consider a Flask app where you use authentication system.
You declare a model User in models.py
:
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(64), unique=True, index=True)
username = db.Column(db.String(64), unique=True, index=True)
password_hash = db.Column(db.String(128))
...
@property
def password(self):
raise AttributeError('password is not a readable attribute')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
In this code we've "hidden" attribute password
by using @property
which triggers AttributeError
assertion when you try to access it directly, while we used @property.setter to set the actual instance variable password_hash
.
Now in auth/views.py
we can instantiate a User with:
...
@auth.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm()
if form.validate_on_submit():
user = User(email=form.email.data,
username=form.username.data,
password=form.password.data)
db.session.add(user)
db.session.commit()
...
Notice attribute password
that comes from a registration form when a user fills the form. Password confirmation happens on the front end with EqualTo('password', message='Passwords must match')
(in case if you are wondering, but it's a different topic related Flask forms).
I hope this example will be useful
In case you want custom names for your createdAt and updatedAt
const mongoose = require('mongoose');
const { Schema } = mongoose;
const schemaOptions = {
timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' },
};
const mySchema = new Schema({ name: String }, schemaOptions);
Developer efficiency matters much more to me in scenarios where both bash and Python are sensible choices.
Some tasks lend themselves well to bash, and others to Python. It also isn't unusual for me to start something as a bash script and change it to Python as it evolves over several weeks.
A big advantage Python has is in corner cases around filename handling, while it has glob, shutil, subprocess, and others for common scripting needs.
Regarding the single quote, see the code below used to replace the string let's
with let us
:
command:
echo "hello, let's go"|sed 's/let'"'"'s/let us/g'
result:
hello, let us go
No.
localStorage is accessible by any webpage, and if you have the key, you can change whatever data you want.
That being said, if you can devise a way to safely encrypt the keys, it doesn't matter how you transfer the data, if you can contain the data within a closure, then the data is (somewhat) safe.
According to wikipedia, it means a "double colon" scope resolution operator.
The answers above were partial. I've spent so much time getting this working, it's insane. Note to my future self, here is what you need to do:
I'm working on Windows 10, with Chrome 65. Firefox is behaving nicely - just confirm localhost as a security exception and it will work. Chrome doesn't:
Step 1. in your backend, create a folder called security
. we will work inside it.
Step 2. create a request config file named req.cnf
with the following content (credit goes to: @Anshul)
req.cnf :
[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = Country initials like US, RO, GE
ST = State
L = Location
O = Organization Name
OU = Organizational Unit
CN = www.localhost.com
[v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = www.localhost.com
DNS.2 = localhost.com
DNS.3 = localhost
An explanation of this fields is here.
Step 3. navigate to the security folder in the terminal and type the following command :
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout cert.key -out cert.pem -config req.cnf -sha256
Step 4. then outside of security
folder, in your express app do something like this: (credit goes to @Diego Mello)
backend
/security
/server.js
server.js:
const express = require('express')
const app = express()
const https = require('https')
const fs = require('fs')
const port = 3000
app.get('/', (req, res) => {
res.send("IT'S WORKING!")
})
const httpsOptions = {
key: fs.readFileSync('./security/cert.key'),
cert: fs.readFileSync('./security/cert.pem')
}
const server = https.createServer(httpsOptions, app)
.listen(port, () => {
console.log('server running at ' + port)
})
Step 5. start the server, node server.js
, and go to https://localhost:3000.
At this point we have the server setup. But the browser should show a warning message.
We need to register our self-signed certificate, as a CA trusted Certificate Authority, in the chrome/windows certificates store. (chrome also saves this in windows,)
Step 6. open Dev Tools in chrome, go to Security panel, then click on View Certificate.
Step 7. go to Details panel, click Copy File, then when the Certificate Export Wizard appears, click Next as below:
Step 8. leave DER encoding, click next, choose Browse
, put it on a easy to access folder like Desktop, and name the certificate localhost.cer, then click Save and then Finish.
. You should be able to see your certificate on Desktop.
Step 9. Open chrome://settings/
by inserting it in the url box. Down below, click on Advanced / Advanced Options
, then scroll down to find Manage Certificates
.
Step 10. Go to Trusted Root Certification Authorities panel, and click import.
We will import the localhost.cer
certificate we just finished exporting in step 8.
Step 11. click browse, find the localhost.cer
, leave the default values click next a bunch of times - until this warning appears, click yes.
Step 12. close everything, and restart chrome. Then, when going to https://localhost:3000
you should see:
While @Andre is correct that there are issues with pseudo elements and their support, especially in older (IE) browsers, that support is improving all the time.
As for your question of, are there any issues, I'd say I've not really seen any, although the syntax for the pseudo-element can be a bit tricky, especially when first sussing it out. So:
div#top-level
declarations: ...
div.inside
declarations: ...
&:first-child
declarations: ...
which compiles as one would expect:
div#top-level{
declarations... }
div#top-level div.inside {
declarations... }
div#top-level div.inside:first-child {
declarations... }
I haven't seen any documentation on any of this, save for the statement that "sass can do everything that css can do." As always, with Haml and SASS the indentation is everything.
If you're looking to scatter by two variables and color by the third, Altair can be a great choice.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.DataFrame(40*np.random.randn(10, 3), columns=['A', 'B','C'])
Altair plot
from altair import *
Chart(df).mark_circle().encode(x='A',y='B', color='C').configure_cell(width=200, height=150)
I would use the get_cmap method. Ex.:
import matplotlib.pyplot as plt
plt.imshow(matrix, cmap=plt.get_cmap('gray'))
i used the following method & it worked fine for me
$('#mybutton').click(function(){
clearForm($('#mybutton').closest("form"));
});
$('#mybutton').closest("form")
did the trick for me.
To trigger the function with click or touch, you could change this:
$(document).click( function () {
To this:
$(document).on('click touchstart', function () {
Or this:
$(document).on('click touch', function () {
The touchstart
event fires as soon as an element is touched, the touch
event is more like a "tap", i.e. a single contact on the surface. You should really try each of these to see what works best for you. On some devices, touch
can be a little harder to trigger (which may be a good or bad thing - it prevents a drag being counted, but an accidental small drag may cause it to not be fired).
What you've got (according to the debug image) is an object array containing a string array. So you need something like:
Object[] objects = (Object[]) values;
String[] strings = (String[]) objects[0];
You haven't shown the type of values
- if this is already Object[]
then you could just use (String[])values[0]
.
Of course even with the cast to Object[]
you could still do it in one statement, but it's ugly:
String[] strings = (String[]) ((Object[])values)[0];
I updated answer of @rdlowrey to a cleaner and better code, This will unzip a file into current directory using __DIR__
.
<?php
// config
// -------------------------------
// only file name + .zip
$zip_filename = "YOURFILENAME.zip";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' >
<title>Unzip</title>
<style>
body{
font-family: arial, sans-serif;
word-wrap: break-word;
}
.wrapper{
padding:20px;
line-height: 1.5;
font-size: 1rem;
}
span{
font-family: 'Consolas', 'courier new', monospace;
background: #eee;
padding:2px;
}
</style>
</head>
<body>
<div class="wrapper">
<?php
echo "Unzipping <span>" .__DIR__. "/" .$zip_filename. "</span> to <span>" .__DIR__. "</span><br>";
echo "current dir: <span>" . __DIR__ . "</span><br>";
$zip = new ZipArchive;
$res = $zip->open(__DIR__ . '/' .$zip_filename);
if ($res === TRUE) {
$zip->extractTo(__DIR__);
$zip->close();
echo '<p style="color:#00C324;">Extract was successful! Enjoy ;)</p><br>';
} else {
echo '<p style="color:red;">Zip file not found!</p><br>';
}
?>
End Script.
</div>
</body>
</html>
I do not understand what this is unclear
Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as though they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily while still providing the safety and flexibility of methods.
In this example, the class TimePeriod stores a time period. Internally the class stores the time in seconds, but a property called Hours is provided that allows a client to specify a time in hours. The accessors for the Hours property perform the conversion between hours and seconds.
Example
class TimePeriod
{
private double seconds;
public double Hours
{
get { return seconds / 3600; }
set { seconds = value * 3600; }
}
}
class Program
{
static void Main()
{
TimePeriod t = new TimePeriod();
// Assigning the Hours property causes the 'set' accessor to be called.
t.Hours = 24;
// Evaluating the Hours property causes the 'get' accessor to be called.
System.Console.WriteLine("Time in hours: " + t.Hours);
}
}
Properties Overview
Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.
A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels.
The value keyword is used to define the value being assigned by the set indexer.
Properties that do not implement a set method are read only.
http://msdn.microsoft.com/en-US/library/x9fsa0sw%28v=vs.80%29.aspx
Type in the command: netstat -aon | findstr :DESIRED_PORT_NUMBER
For example, if I want to find port 80: netstat -aon | findstr :80
This answer was originally posted to this question.
I put my customized changes in the User package:
*nix: ~/.config/sublime-text-2/Packages/User/Scala.tmLanguage
*Windows: %APPDATA%\Sublime Text 2\Packages\User\Scala.tmLanguage
Which also means it's in JSON format:
{
"extensions":
[
"sbt"
]
}
This is the same place the
View -> Syntax -> Open all with current extension as ...
menu item adds it (creating the file if it doesn't exist).
You can use this
"abcdefg".index('c') #=> 2
I have received com.sun.jdi.InvocationException occurred invoking method
when I lazy loaded entity field which used secondary database config (Spring Boot with 2 database configs - lazy loading with second config does not work). Temporary solution was to add FetchType.EAGER
.
You can easily launch Firefox from the command line with a proxy server using the -proxy-server option.
This works on Mac, Windows and Linux.
path_to_firefox/firefox.exe -proxy-server %proxy_URL%
Mac Example:
/Applications/Firefox.app/Contents/MacOS/firefox -proxy-server proxy.example.com
I understand that the C syntax !=
is in SQL Server due to its Unix heritage (back in the Sybase SQL Server days, pre Microsoft SQL Server 6.5).