Had the same error initially. so.. pre-installed git and node.js and later installed Aptana, which installed perfectly. Rajeeva.
Postgresql does not have an equivalent of Oracle's ROWNUM. In many cases you can achieve the same result by using LIMIT and OFFSET in your query.
This \ means "the root directory of the current drive". In your example it means the "test" folder in the current drive's root directory. So, this can be equal to "c:\test".
I found that an answer to this issue when dealing with math is that the operator on the left hand side must be the variable you are trying to change. The logic cannot come first.
coin1 + coin2 + coin3 = coinTotal; // Wrong
coinTotal = coin1 + coin2 + coin3; // Right
This isn't a direct answer to your question but it might be helpful to future people who google the same thing I googled.
Thanks to AddRange
:
Example:
public class Person
{
private string Name;
private string FirstName;
public Person(string name, string firstname) => (Name, FirstName) = (name, firstname);
}
To add multiple Person
to a List<>
:
List<Person> listofPersons = new List<Person>();
listofPersons.AddRange(new List<Person>
{
new Person("John1", "Doe" ),
new Person("John2", "Doe" ),
new Person("John3", "Doe" ),
});
keyCodes are different from the ASCII values. For a complete keyCode reference, see http://unixpapa.com/js/key.html
For example, Numpad numbers have keyCodes 96 - 105, which corresponds to the beginning of lowercase alphabet in ASCII. This could lead to problems in validating numeric input.
select *
from
tableA a
inner join
tableB b
on a.common = b.common
inner join
TableC c
on b.common = c.common
See https://help.github.com/articles/duplicating-a-repository
Short version:
In order to make an exact duplicate, you need to perform both a bare-clone and a mirror-push:
mkdir foo; cd foo
# move to a scratch dir
git clone --bare https://github.com/exampleuser/old-repository.git
# Make a bare clone of the repository
cd old-repository.git
git push --mirror https://github.com/exampleuser/new-repository.git
# Mirror-push to the new repository
cd ..
rm -rf old-repository.git
# Remove our temporary local repository
NOTE: the above will work fine with any remote git repo, the instructions are not specific to github
The above creates a new remote copy of the repo. Then clone it down to your working machine.
Some other ideas not mentioned yet:
switch(true){
case in_array($p, array('home', '')):
$current_home = 'current'; break;
case preg_match('/^users\.(online|location|featured|new|browse|search|staff)$/', $p):
$current_users = 'current'; break;
case 'forum' == $p:
$current_forum = 'current'; break;
}
Someone will probably complain about readability issues with #2, but I would have no problem inheriting code like that.
The latest (as of Jan 2019) stand-alone MSBuild installers can be found here: https://www.visualstudio.com/downloads/
Scroll down to "Tools for Visual Studio 2019" and choose "Build Tools for Visual Studio 2019" (despite the name, it's for users who don't want the full IDE)
See this question for additional information.
Simple answer : free(testPerson)
is enough .
Remember you can use free()
only when you have allocated memory using malloc
, calloc
or realloc
.
In your case you have only malloced memory for testPerson
so freeing that is sufficient.
If you have used char * firstname , *last surName
then in that case to store name you must have allocated the memory and that's why you had to free each member individually.
Here is also a point it should be in the reverse order; that means, the memory allocated for elements is done later so free()
it first then free the pointer to object.
Freeing each element you can see the demo shown below:
typedef struct Person
{
char * firstname , *last surName;
}Person;
Person *ptrobj =malloc(sizeof(Person)); // memory allocation for struct
ptrobj->firstname = malloc(n); // memory allocation for firstname
ptrobj->surName = malloc(m); // memory allocation for surName
.
. // do whatever you want
free(ptrobj->surName);
free(ptrobj->firstname);
free(ptrobj);
The reason behind this is, if you free the ptrobj
first, then there will be memory leaked which is the memory allocated by firstname
and suName
pointers.
maps.google.com has a navigation service which can provide you route information in KML format.
To get kml file we need to form url with start and destination locations:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon) {// connect to map web service
StringBuffer urlString = new StringBuffer();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");// from
urlString.append(Double.toString(fromLat));
urlString.append(",");
urlString.append(Double.toString(fromLon));
urlString.append("&daddr=");// to
urlString.append(Double.toString(toLat));
urlString.append(",");
urlString.append(Double.toString(toLon));
urlString.append("&ie=UTF8&0&om=0&output=kml");
return urlString.toString();
}
Next you will need to parse xml (implemented with SAXParser) and fill data structures:
public class Point {
String mName;
String mDescription;
String mIconUrl;
double mLatitude;
double mLongitude;
}
public class Road {
public String mName;
public String mDescription;
public int mColor;
public int mWidth;
public double[][] mRoute = new double[][] {};
public Point[] mPoints = new Point[] {};
}
Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon)
then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:
public static Road getRoute(InputStream is)
Full source code RoadProvider.java
class MapPathScreen extends MainScreen {
MapControl map;
Road mRoad = new Road();
public MapPathScreen() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
map = new MapControl();
add(new LabelField(mRoad.mName));
add(new LabelField(mRoad.mDescription));
add(map);
}
protected void onUiEngineAttached(boolean attached) {
super.onUiEngineAttached(attached);
if (attached) {
map.drawPath(mRoad);
}
}
private InputStream getConnection(String url) {
HttpConnection urlConnection = null;
InputStream is = null;
try {
urlConnection = (HttpConnection) Connector.open(url);
urlConnection.setRequestMethod("GET");
is = urlConnection.openInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}
See full code on J2MEMapRouteBlackBerryEx on Google Code
public class MapRouteActivity extends MapActivity {
LinearLayout linearLayout;
MapView mapView;
private Road mRoad;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
new Thread() {
@Override
public void run() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider
.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
mHandler.sendEmptyMessage(0);
}
}.start();
}
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
TextView textView = (TextView) findViewById(R.id.description);
textView.setText(mRoad.mName + " " + mRoad.mDescription);
MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
};
};
private InputStream getConnection(String url) {
InputStream is = null;
try {
URLConnection conn = new URL(url).openConnection();
is = conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
See full code on J2MEMapRouteAndroidEx on Google Code
MVC4 Quick Tip #3–Removing the XML Formatter from ASP.Net Web API
In Global.asax
add the line:
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
like so:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
BundleTable.Bundles.RegisterTemplateBundles();
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
}
Use DatatypeConverter.printHexBinary()
:
public static String toHexadecimal(String text) throws UnsupportedEncodingException
{
byte[] myBytes = text.getBytes("UTF-8");
return DatatypeConverter.printHexBinary(myBytes);
}
Example usage:
System.out.println(toHexadecimal("Hello StackOverflow"));
Prints:
48656C6C6F20537461636B4F766572666C6F77
Note: This causes a little extra trouble with Java 9
and newer since the API is not included by default. For reference e.g. see this GitHub
issue.
Unfortunately, the answer to your question of whether there is official Material support for selecting the time is "No", but it's currently an open issue on the official Material2 GitHub repo: https://github.com/angular/material2/issues/5648
Hopefully this changes soon, in the mean time, you'll have to fight with the 3rd-party ones you've already discovered. There are a few people in that GitHub issue that provide their self-made workarounds that you can try.
<select name="career" id="career" onchange="location = this.value;">
<option value="resume" selected> All Applications </option>
<option value="resume&j=14">Seo Expert</option>
<option value="resume&j=21">Project Manager</option>
<option value="resume&j=33">Php Developer</option>
</select>
The pattern matches all non-digit characters. This will restrict you to non-negative integers, but for your example it will be more than sufficient.
string input = "0, 10, 20, 30, 100, 200";
Regex.Split(input, @"\D+");
A4 size is 210x297mm
So you can set the HTML page to fit those sizes with CSS:
html,body{
height:297mm;
width:210mm;
}
You can use a watchpoint for this (A breakpoint on data instead of code).
You can start by using watch i
.
Then set a condition for it using condition <breakpoint num> i == 5
You can get the breakpoint number by using info watch
List<Person> roster = ...;
Map<String, Person> map =
roster
.stream()
.collect(
Collectors.toMap(p -> p.getLast(), p -> p)
);
that would be the translation, but i havent run this or used the API. most likely you can substitute p -> p, for Function.identity(). and statically import toMap(...)
It's basically the same mechanism as for a non query command with:
CommandType.StoredProcedure
There are plenty of examples out there, the first one returned by Google is this one
There's also a little trap you might fall into, if your SP is a function, your return value parameter must be first in the parameters collection
Try This :
<input min="0" max="100" id="when_change_range" type="range">
<input type="text" id="text_for_show_range">
and in jQuery section :
$('#when_change_range').change(function(){
document.getElementById('text_for_show_range').value=$(this).val();
});
Above of all, I found this library right here. Works out of the box perfectly on a Bootstrap-3 environment.
CSS
<link rel="stylesheet" type="text/css" href="dist/bootstrap-clockpicker.min.css">
HTML
<div class="input-group clockpicker">
<input type="text" class="form-control" value="09:30">
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
JAVASCRIPT
<script type="text/javascript" src="dist/bootstrap-clockpicker.min.js"></script>
<script type="text/javascript">
$('.clockpicker').clockpicker();
</script>
As simple as that! Find more examples on the link above.
If you are using Bootstrap-4, the most popular time/date picker library available right now is Tempus Dominus. It is not fancy looking, but much responsive and modern.
Don't worry...! Follow these below steps and you will get your signed .apk file. I was also worry about that, but these step get ride me off from the frustration. Steps to sign your application:
Right click on the project in Eclipse -> Android Tools -> Export Unsigned Application Package (like here we export our GoogleDriveApp.apk to Desktop)
Sign the application using your keystore and the jarsigner tool (follow below steps):
Open cmd-->change directory where your "jarsigner.exe" exist (like here in my system it exist at "C:\Program Files\Java\jdk1.6.0_17\bin"
Now enter belwo command in cmd:
jarsigner -verbose -keystore c:\users\android\debug.keystore c:\users\pir fahim\Desktops\GoogleDriveApp.apk my_keystore_alias
It will ask you to provide your password: Enter Passphrase for keystore: It will sign your apk.To verify that the signing is successful you can run:
jarsigner -verify c:\users\pir fahim\Desktops\GoogleDriveApp.apk
It should come back with: jar verified.
Method 2
If you are using eclipse with ADT, then it is simple to compiled, signed, aligned, and ready the file for distribution.what you have to do just follow this steps.
These steps will compiled, signed and zip aligned your project and now you are ready to distribute your project or upload at Google Play store.
I don't see an obvious problem with the above.
It's possible your ldap.conf
is being overridden, but the command-line options will take precedence, ldapsearch
will ignore BINDDN
in the main ldap.conf
, so the only parameter that could be wrong is the URI.
(The order is ETCDIR/ldap.conf
then ~/ldaprc
or ~/.ldaprc
and then ldaprc
in the current directory, though there environment variables which can influence this too, see man ldapconf
.)
Try an explicit URI:
ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost
or prevent defaults with:
LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd
binary for these):
make sure your slapd.conf
is being used and is correct (as root)
slapd -T test -f slapd.conf -d 65535
You may have a left-over or default slapd.d
configuration directory which takes preference over your slapd.conf
(unless you specify your config explicitly with -f
, slapd.conf
is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.
stop OpenLDAP, then manually start slapd
in a separate terminal/console with debug enabled (as root, ^C to quit)
slapd -h ldap://localhost -d 481
then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd
without the -u
/-g
options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap
)
if debug is enabled, then try also
ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
As others have pointed to CSS specification, percentages aren't supported on borders:
'border-top-width',
'border-right-width',
'border-bottom-width',
'border-left-width'
Value: <border-width> | inherit
Initial: medium
Applies to: all elements
Inherited: no
Percentages: N/A
Media: visual
Computed value: absolute length; '0' if the border style is 'none' or 'hidden'
As you can see it says Percentages: N/A.
You can simulate your percentage borders with a wrapper element where you would:
background-color
to your desired border colourpadding
in percentages (because they're supported)background-color
to white (or whatever it needs to be)This would somehow simulate your percentage borders. Here's an example of an element with 25% width side borders that uses this technique.
HTML used in the example
.faux-borders {_x000D_
background-color: #f00;_x000D_
padding: 1px 25%; /* set padding to simulate border */_x000D_
}_x000D_
.content {_x000D_
background-color: #fff;_x000D_
}
_x000D_
<div class="faux-borders">_x000D_
<div class="content">_x000D_
This is the element to have percentage borders._x000D_
</div>_x000D_
</div>
_x000D_
Issue: You have to be aware that this will be much more complicated when your element has some complex background applied to it... Especially if that background is inherited from ancestor DOM hierarchy. But if your UI is simple enough, you can do it this way.
@BoltClock mentioned scripted solution where you can programmaticaly calculate border width according to element size.
This is such an example with extremely simple script using jQuery.
var el = $(".content");_x000D_
var w = el.width() / 4 | 0; // calculate & trim decimals_x000D_
el.css("border-width", "1px " + w + "px");
_x000D_
.content { border: 1px solid #f00; }
_x000D_
<div class="content">_x000D_
This is the element to have percentage borders._x000D_
</div>
_x000D_
But you have to be aware that you will have to adjust border width every time your container size changes (i.e. browser window resize). My first workaround with wrapper element seems much simpler because it will automatically adjust width in these situations.
The positive side of scripted solution is that it doesn't suffer from background problems mentioned in my previous non-scripted solution.
From your local machine:
rsync -chavzP --stats [email protected]:/path/to/copy /path/to/local/storage
From your local machine with a non standard ssh port:
rsync -chavzP -e "ssh -p $portNumber" [email protected]:/path/to/copy /local/path
Or from the remote host, assuming you really want to work this way and your local machine is listening on SSH:
rsync -chavzP --stats /path/to/copy [email protected]:/path/to/local/storage
See man rsync
for an explanation of my usual switches.
Its very simple you just add this script,
$("#mydate").datepicker({ dateFormat: "yy-mm-dd"}).datepicker("setDate", new Date());
Here, setDate set today date & dateFormat define which format you want set or show.
Hope its simple script work..
I just did this last week. Set the GrowStyle
on the TableLayoutPanel
to AddRows
or AddColumns
, then your code should work:
// Adds "myControl" to the first column of each row
myTableLayoutPanel.Controls.Add(myControl1, 0 /* Column Index */, 0 /* Row index */);
myTableLayoutPanel.Controls.Add(myControl2, 0 /* Column Index */, 1 /* Row index */);
myTableLayoutPanel.Controls.Add(myControl3, 0 /* Column Index */, 2 /* Row index */);
Here is some working code that seems similar to what you are doing:
private Int32 tlpRowCount = 0;
private void BindAddress()
{
Addlabel(Addresses.Street);
if (!String.IsNullOrEmpty(Addresses.Street2))
{
Addlabel(Addresses.Street2);
}
Addlabel(Addresses.CityStateZip);
if (!String.IsNullOrEmpty(Account.Country))
{
Addlabel(Address.Country);
}
Addlabel(String.Empty); // Notice the empty label...
}
private void Addlabel(String text)
{
label = new Label();
label.Dock = DockStyle.Fill;
label.Text = text;
label.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
tlpAddress.Controls.Add(label, 1, tlpRowCount);
tlpRowCount++;
}
The TableLayoutPanel
always gives me fits with size. In my example above, I'm filing an address card that might grow or shrink depending on the account having an address line two, or a country. Because the last row, or column, of the table layout panel will stretch, I throw the empty label in there to force a new empty row, then everything lines up nicely.
Here is the designer code so you can see the table I start with:
//
// tlpAddress
//
this.tlpAddress.AutoSize = true;
this.tlpAddress.BackColor = System.Drawing.Color.Transparent;
this.tlpAddress.ColumnCount = 2;
this.tlpAddress.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 25F));
this.tlpAddress.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tlpAddress.Controls.Add(this.pictureBox1, 0, 0);
this.tlpAddress.Dock = System.Windows.Forms.DockStyle.Fill;
this.tlpAddress.Location = new System.Drawing.Point(0, 0);
this.tlpAddress.Name = "tlpAddress";
this.tlpAddress.Padding = new System.Windows.Forms.Padding(3);
this.tlpAddress.RowCount = 2;
this.tlpAddress.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tlpAddress.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tlpAddress.Size = new System.Drawing.Size(220, 95);
this.tlpAddress.TabIndex = 0;
I am able to use this feature on my machine using MS Access 2007.
For what its worth, I'm using Access 2007 SP1
Try these solutions, for maximum compatibility, as I have already posted here:
JavaScript:
var nm_re = /^(?:((([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-.\s])){1,}(['’,\-\.]){0,1}){2,}(([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-. ]))*(([ ]+){0,1}(((([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-\.\s])){1,})(['’\-,\.]){0,1}){2,}((([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-\.\s])){2,})?)*)$/;
HTML5:
<input type="text" name="full_name" id="full_name" pattern="^(?:((([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-.\s])){1,}(['’,\-\.]){0,1}){2,}(([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-. ]))*(([ ]+){0,1}(((([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-\.\s])){1,})(['’\-,\.]){0,1}){2,}((([^0-9_!¡?÷?¿/\\+=@#$%ˆ&*(){}|~<>;:[\]'’,\-\.\s])){2,})?)*)$" required>
I was trying to concatenate three .mp3
audio files into one .m4a
file and this ffmpeg command works.
Input command:
ffmpeg -i input1.mp3 -i input2.mp3 -i input3.mp3 \
-filter_complex "concat=n=3:v=0:a=1" -f MOV -vn -y input.m4a
Meanings of :
-filter_complex "concat=n=3:v=0:a=1" :
concat means use the media concatenate (joining) function.
n means confirm total count of input files.
v means has video? use 0 = no video, 1 = contains video.
a means has audio? use 0 = no audio, 1 = contain audio.
-f means force set file format (to see all supported formats, useffmpeg -formats
)
-vn means disable video (and also-an
would disable audio if not wanted)
-y means overwrite output files (if the output file already exists).
For more info: use ffmpeg -h full
print all options (including all format and codec specific options, very long)
You can use the trim() method in a Swift String extension I wrote https://bit.ly/JString.
var string = "hello "
var trimmed = string.trim()
println(trimmed)// "hello"
Assuming you're using a std::ofstream
to write to file, the following snippet will write a std::string
to file in human readable form:
std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;
Here's a solution if you just want to update certain components on a page:
In template
<Component1 :key="forceReload" />
<Component2 :key="forceReload" />
In data
data() {
return {
forceReload: 0
{
}
In methods:
Methods: {
reload() {
this.forceReload += 1
}
}
Use a unique key and bind it to a data property for each one you want to update (I typically only need this for a single component, two at the most. If you need more, I suggest just refreshing the full page using the other answers.
I learned this from Michael Thiessen's post: https://medium.com/hackernoon/the-correct-way-to-force-vue-to-re-render-a-component-bde2caae34ad
Suppose you want to use, say ID in any other webpage then you can do it by following code snippet :
String id=(String)session.getAttribute("uid");
Here uid is the attribute in which you have stored the ID earlier. You can set it by:
session.setAttribute("uid",id);
The following will cover all browsers worth covering:
text-shadow: 0 0 2px #fff; /* Firefox 3.5+, Opera 9+, Safari 1+, Chrome, IE10 */
filter: progid:DXImageTransform.Microsoft.Glow(Color=#ffffff,Strength=1); /* IE<10 */
In my opinion, it's a way to implement currying in python.
from functools import partial
def add(a,b):
return a + b
def add2number(x,y,z):
return x + y + z
if __name__ == "__main__":
add2 = partial(add,2)
print("result of add2 ",add2(1))
add3 = partial(partial(add2number,1),2)
print("result of add3",add3(1))
The result is 3 and 4.
Another way to do this problem besides using ASCII conversions is the following:
String input = "abc".toLowerCase();
final static String alphabet = "abcdefghijklmnopqrstuvwxyz";
for(int i=0; i < input.length(); i++){
System.out.print(alphabet.indexOf(input.charAt(i))+1);
}
Much easier way to view the signing certificate:
jarsigner.exe -verbose -verify -certs myapk.apk
This will only show the DN, so if you have two certs with the same DN, you might have to compare by fingerprint.
One statement can be written as such:
someValues.forEach(x => console.log(x));
or multiple statements can be enclosed in {}
like this:
someValues.forEach(x => { let a = 2 + x; console.log(a); });
Definitely the second method is preferred because you don't have the overhead of another function invocation:
window.location.href = "webpage.htm";
Is this what you're after?
I added :text-align:center
to the div and image
ng --version
command will show only the installed angular version in your computer instead of the actual project version.
if you really want to know the project version, Go to your project, use the below command
npm list -local
I don't know if I would say heredoc is laziness. One can say that doing anything is laziness, as there are always more cumbersome ways to do anything.
For example, in certain situations you may want to output text, with embedded variables without having to fetch from a file and run a template replace. Heredoc allows you to forgo having to escape quotes, so the text you see is the text you output. Clearly there are some negatives, for example, you can't indent your heredoc, and that can get frustrating in certain situation, especially if your a stickler for unified syntax, which I am.
This depends on the language being used. You wrote 'language-agnostic', so I'll give some examples.
In Java, C, and Python, recursion is fairly expensive compared to iteration (in general) because it requires the allocation of a new stack frame. In some C compilers, one can use a compiler flag to eliminate this overhead, which transforms certain types of recursion (actually, certain types of tail calls) into jumps instead of function calls.
In functional programming language implementations, sometimes, iteration can be very expensive and recursion can be very cheap. In many, recursion is transformed into a simple jump, but changing the loop variable (which is mutable) sometimes requires some relatively heavy operations, especially on implementations which support multiple threads of execution. Mutation is expensive in some of these environments because of the interaction between the mutator and the garbage collector, if both might be running at the same time.
I know that in some Scheme implementations, recursion will generally be faster than looping.
In short, the answer depends on the code and the implementation. Use whatever style you prefer. If you're using a functional language, recursion might be faster. If you're using an imperative language, iteration is probably faster. In some environments, both methods will result in the same assembly being generated (put that in your pipe and smoke it).
Addendum: In some environments, the best alternative is neither recursion nor iteration but instead higher order functions. These include "map", "filter", and "reduce" (which is also called "fold"). Not only are these the preferred style, not only are they often cleaner, but in some environments these functions are the first (or only) to get a boost from automatic parallelization — so they can be significantly faster than either iteration or recursion. Data Parallel Haskell is an example of such an environment.
List comprehensions are another alternative, but these are usually just syntactic sugar for iteration, recursion, or higher order functions.
The upside-down A symbol is the universal quantifier from predicate logic. (Also see the more complete discussion of the first-order predicate calculus.) As others noted, it means that the stated assertions holds "for all instances" of the given variable (here, s). You'll soon run into its sibling, the backwards capital E, which is the existential quantifier, meaning "there exists at least one" of the given variable conforming to the related assertion.
If you're interested in logic, you might enjoy the book Logic and Databases: The Roots of Relational Theory by C.J. Date. There are several chapters covering these quantifiers and their logical implications. You don't have to be working with databases to benefit from this book's coverage of logic.
myList.RemoveAt(i--);
simples;
There are three possibilities:
1) If you are referring old DLL then it cant be used. So you have refer new DLL
2) If you are using it in different namespace and trying to use the other namespace's dll then it wont refer this method.
3) You may need to rebuild the project
I think third option might be the cause for you. Please post more information in order to understand exact problem of yours.
Do you really need to "build" it from javascript or can you simply return the built HTML from PHP and insert it into the DOM?
A simple code :
var homes = [_x000D_
{_x000D_
"h_id": "3",_x000D_
"city": "Dallas",_x000D_
"state": "TX",_x000D_
"zip": "75201",_x000D_
"price": "162500"_x000D_
}, {_x000D_
"h_id": "4",_x000D_
"city": "Bevery Hills",_x000D_
"state": "CA",_x000D_
"zip": "90210",_x000D_
"price": "319250"_x000D_
}, {_x000D_
"h_id": "5",_x000D_
"city": "New York",_x000D_
"state": "NY",_x000D_
"zip": "00010",_x000D_
"price": "962500"_x000D_
}_x000D_
];_x000D_
_x000D_
let sortByPrice = homes.sort(function (a, b) _x000D_
{_x000D_
return parseFloat(b.price) - parseFloat(a.price);_x000D_
});_x000D_
_x000D_
for (var i=0; i<sortByPrice.length; i++)_x000D_
{_x000D_
document.write(sortByPrice[i].h_id+' '+sortByPrice[i].city+' '_x000D_
+sortByPrice[i].state+' '_x000D_
+sortByPrice[i].zip+' '+sortByPrice[i].price);_x000D_
document.write("<br>");_x000D_
}
_x000D_
I think if you are looking for fullscreen only, no need to set geometry or maxsize etc.
You just need to do this:
-If you are working on ubuntu:
root=tk.Tk()
root.attributes('-zoomed', True)
-and if you are working on windows:
root.state('zoomed')
Now for toggling between fullscreen, for minimising it to taskbar you can use:
Root.iconify()
The following was tested for IIS 8.5 and Windows 8.1.
As of IIS 7, Windows recommends restarting IIS via net stop/start
. Via the command prompt (as Administrator):
> net stop WAS
> net start W3SVC
net stop WAS
will stop W3SVC
as well. Then when starting, net start W3SVC
will start WAS
as a dependency.
Stacks for threads are often smaller. You can change the default at link time, or change at run time also. For reference, some defaults are:
If you absolutely want to combine integers and NaNs in a column, you can use the 'object' data type:
df['col'] = (
df['col'].fillna(0)
.astype(int)
.astype(object)
.where(df['col'].notnull())
)
This will replace NaNs with an integer (doesn't matter which), convert to int, convert to object and finally reinsert NaNs.
var html = "";
for (var i = 0; i < data.length; i++){
html +="<tr>"+
"<td>"+ (i+1) + "</td>"+
"<td>"+ data[i].name + "</td>"+
"<td>"+ data[i].number + "</td>"+
"<td>"+ data[i].city + "</td>"+
"<td>"+ data[i].hobby + "</td>"+
"<td>"+ data[i].birthdate + "</td>"+"<td><button data-arrayIndex='"+ i +"' onclick='editData(this)'>Edit</button><button data-arrayIndex='"+ i +"' onclick='deleteData()'>Delete</button></td>"+"</tr>";
}
$("#tableHtml").html(html);
If you don't know which extension you have, then you can try this:
$ext = strtolower(substr('yourFileName.ext', strrpos('yourFileName.ext', '.') + 1));
echo basename('yourFileName.ext','.'.$ext); // output: "youFileName" only
Working with all possibilities:
image.jpg // output: "image"
filename.image.png // output: "filename.image"
index.php // output: "index"
Try with
f.mkdirs()
then createNewFile()
the secure way is encrypt your sensitive data by AES and the encryption key is derivation by password-based key derivation function (PBE), the master password used to encrypt/decrypt the encrypt key for AES.
master password -> secure key-> encrypt data by the key
You can use pbkdf2
from PBKDF2 import PBKDF2
from Crypto.Cipher import AES
import os
salt = os.urandom(8) # 64-bit salt
key = PBKDF2("This passphrase is a secret.", salt).read(32) # 256-bit key
iv = os.urandom(16) # 128-bit IV
cipher = AES.new(key, AES.MODE_CBC, iv)
make sure to store the salt/iv/passphrase , and decrypt using same salt/iv/passphase
Weblogic used similar approach to protect passwords in config files
The file permission is okay (0777) but i think your on the shared server, so to delete your file correctly use; 1. create a correct path to your file
// delete from folder
$filename = 'test.txt';
$ifile = '/newy/made/link/uploads/'. $filename; // this is the actual path to the file you want to delete.
unlink($_SERVER['DOCUMENT_ROOT'] .$ifile); // use server document root
// your file will be removed from the folder
That small code will do the magic and remove any selected file you want from any folder provided the actual file path is collect.
Indexing a list is done using double bracket, i.e. hypo_list[[1]]
(e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table
does not return a table but a dataframe (see value section in ?read.table
). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.
Note: In R, the index for the first entry is a 1
(not 0
like in some other languages).
Dataframes
l <- list(anscombe, iris) # put dfs in list
l[[1]] # returns anscombe dataframe
anscombe[1:2, 2] # access first two rows and second column of dataset
[1] 10 8
l[[1]][1:2, 2] # the same but selecting the dataframe from the list first
[1] 10 8
Table objects
tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2) # put tables in a list
tbl1[1:2] # access first two elements of table 1
Now with the list
l[[1]] # access first table from the list
1 2 3 4 5
9 11 12 9 9
l[[1]][1:2] # access first two elements in first table
1 2
9 11
I solved my problem by upgrading my .NetFramework version from 4.5.2 to 4.7.2.
Try deleting the .jenkins folder from your system which is located ate the below path. C:\Users\"Your PC Name".jenkins
Now download a fresh and a stable version of .war file from official website of jenkins. For eg. 2.1 and follow the steps to install.
You can get the difference between two DateTime using this
DateTime startDate = DateTime.now();
DateTime endDate = DateTime.now();
Days daysBetween = Days.daysBetween(startDate, endDate);
System.out.println(daysBetween.toStandardSeconds());
You can't reference an alias except in ORDER BY because SELECT is the second last clause that's evaluated. Two workarounds:
SELECT BalanceDue FROM (
SELECT (InvoiceTotal - PaymentTotal - CreditTotal) AS BalanceDue
FROM Invoices
) AS x
WHERE BalanceDue > 0;
Or just repeat the expression:
SELECT (InvoiceTotal - PaymentTotal - CreditTotal) AS BalanceDue
FROM Invoices
WHERE (InvoiceTotal - PaymentTotal - CreditTotal) > 0;
I prefer the latter. If the expression is extremely complex (or costly to calculate) you should probably consider a computed column (and perhaps persisted) instead, especially if a lot of queries refer to this same expression.
PS your fears seem unfounded. In this simple example at least, SQL Server is smart enough to only perform the calculation once, even though you've referenced it twice. Go ahead and compare the plans; you'll see they're identical. If you have a more complex case where you see the expression evaluated multiple times, please post the more complex query and the plans.
Here are 5 example queries that all yield the exact same execution plan:
SELECT LEN(name) + column_id AS x
FROM sys.all_columns
WHERE LEN(name) + column_id > 30;
SELECT x FROM (
SELECT LEN(name) + column_id AS x
FROM sys.all_columns
) AS x
WHERE x > 30;
SELECT LEN(name) + column_id AS x
FROM sys.all_columns
WHERE column_id + LEN(name) > 30;
SELECT name, column_id, x FROM (
SELECT name, column_id, LEN(name) + column_id AS x
FROM sys.all_columns
) AS x
WHERE x > 30;
SELECT name, column_id, x FROM (
SELECT name, column_id, LEN(name) + column_id AS x
FROM sys.all_columns
) AS x
WHERE LEN(name) + column_id > 30;
Resulting plan for all five queries:
No jQuery:
// Return an array of the selected opion values
// select is an HTML select element
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
Quick example:
<select multiple>
<option>opt 1 text
<option value="opt 2 value">opt 2 text
</select>
<button onclick="
var el = document.getElementsByTagName('select')[0];
alert(getSelectValues(el));
">Show selected values</button>
-- DON'T FORGET TO BACKUP THE DB :D (Check [here][1])
USE AdventureWorks2008R2;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE AdventureWorks2008R2
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (AdventureWorks2008R2_Log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE AdventureWorks2008R2
SET RECOVERY FULL;
GO
From: DBCC SHRINKFILE (Transact-SQL)
You may want to backup first.
This solution is useful when your object has Specific Type. Like when obtaining the object to other source.
let user: User = new User();
(user as any).otherProperty = 'hello';
//user did not lose its type here.
The above answer was helpful for me, but it might be useful (or best practice) to add the name on submit, as I wound up doing. Hopefully this will be helpful to someone. CodePen Sample
<form id="formAddName">
<fieldset>
<legend>Add Name </legend>
<label for="firstName">First Name</label>
<input type="text" id="firstName" name="firstName" />
<button>Add</button>
</fieldset>
</form>
<ol id="demo"></ol>
<script>
var list = document.getElementById('demo');
var entry = document.getElementById('formAddName');
entry.onsubmit = function(evt) {
evt.preventDefault();
var firstName = document.getElementById('firstName').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(firstName));
list.appendChild(entry);
}
</script>
You say you don't necessarily know that 'key2' is in position [1]. Well, it's not. Position 1 would be occupied by myHash[1].
You're abusing JavaScript arrays, which (like functions) allow key/value hashes. Even though JavaScript allows it, it does not give you facilities to deal with it, as a language designed for associative arrays would. JavaScript's array methods work with the numbered properties only.
The first thing you should do is switch to objects rather than arrays. You don't have a good reason to use an array here rather than an object, so don't do it. If you want to use an array, just number the elements and give up on the idea of hashes. The intent of an array is to hold information which can be indexed into numerically.
You can, of course, put a hash (object) into an array if you like.
myhash[1]={"key1","brightOrangeMonkey"};
The actual information represented by a boolean value in Java is one bit: 1 for true, 0 for false. However, the actual size of a boolean variable in memory is not precisely defined by the Java specification. See Primitive Data Types in Java.
The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.
An alternative approach if interested - with an extra intermediate class to use the normal OOO way. This simplifies the usage with parent::methodname
trait A {
function calc($v) {
return $v+1;
}
}
// an intermediate class that just uses the trait
class IntClass {
use A;
}
// an extended class from IntClass
class MyClass extends IntClass {
function calc($v) {
$v++;
return parent::calc($v);
}
}
The readarray
command (also spelled mapfile
) was introduced in bash 4.0.
readarray -t a < /path/to/filename
For a concise way to retain the folder hierarchy under the parent directory to be archived:
import glob
import zipfile
with zipfile.ZipFile(fp_zip, "w", zipfile.ZIP_DEFLATED) as zipf:
for fp in glob(os.path.join(parent, "**/*")):
base = os.path.commonpath([parent, fp])
zipf.write(fp, arcname=fp.replace(base, ""))
If you want, you could change this to use pathlib
for file globbing.
You can try my lib for multiple bluetooth connection :
You likely want to use onupdate=datetime.now
so that UPDATEs also change the last_updated
field.
SQLAlchemy has two defaults for python executed functions.
default
sets the value on INSERT, only onceonupdate
sets the value to the callable result on UPDATE as well.The package @angular/router
has the Resolve
property for routes. So you can easily resolve data before rendering a route view.
See: https://angular.io/docs/ts/latest/api/router/index/Resolve-interface.html
Example from docs as of today, August 28, 2017:
class Backend {
fetchTeam(id: string) {
return 'someTeam';
}
}
@Injectable()
class TeamResolver implements Resolve<Team> {
constructor(private backend: Backend) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<any>|Promise<any>|any {
return this.backend.fetchTeam(route.params.id);
}
}
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'team/:id',
component: TeamCmp,
resolve: {
team: TeamResolver
}
}
])
],
providers: [TeamResolver]
})
class AppModule {}
Now your route will not be activated until the data has been resolved and returned.
Accessing Resolved Data In Your Component
To access the resolved data from within your component at runtime, there are two methods. So depending on your needs, you can use either:
route.snapshot.paramMap
which returns a string, or the route.paramMap
which returns an Observable you can .subscribe()
to. Example:
// the no-observable method
this.dataYouResolved= this.route.snapshot.paramMap.get('id');
// console.debug(this.licenseNumber);
// or the observable method
this.route.paramMap
.subscribe((params: ParamMap) => {
// console.log(params);
this.dataYouResolved= params.get('id');
return params.get('dataYouResolved');
// return null
});
console.debug(this.dataYouResolved);
I hope that helps.
I've personally used templates of late to handle multiple types of containers at once rather than deal only with vectors. I found a similar example online (can't remember where) so credit goes to whoever I've pilfered this from. This particular pattern seems to handle raw arrays as well.
template <typename Container, typename T = typename std::decay<decltype(*std::begin(std::declval<Container>()))>::type>
bool contains(Container && c, T v)
{
return std::find(std::begin(c), std::end(c), v) != std::end(c);
}
In addition to the accepted answer I would like to give an answer that shows how to iterate directly over the Newtonsoft collections. It uses less code and I'm guessing its more efficient as it doesn't involve converting the collections.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//Parse the data
JObject my_obj = JsonConvert.DeserializeObject<JObject>(your_json);
foreach (KeyValuePair<string, JToken> sub_obj in (JObject)my_obj["ADDRESS_MAP"])
{
Console.WriteLine(sub_obj.Key);
}
I started doing this myself because JsonConvert automatically deserializes nested objects as JToken (which are JObject, JValue, or JArray underneath I think).
I think the parsing works according to the following principles:
Every object is abstracted as a JToken
Cast to JObject where you expect a Dictionary
Cast to JValue if the JToken represents a terminal node and is a value
Cast to JArray if its an array
JValue.Value gives you the .NET type you need
ArrayList<Customer> custArr = new ArrayList<Customer>();
while(youWantToContinue) {
//get a customerName
//get an amount
custArr.add(new Customer(customerName, amount);
}
For this to work... you'll have to fix your constructor...
Assuming your Customer
class has variables called name
and sale
, your constructor should look like this:
public Customer(String customerName, double amount) {
name = customerName;
sale = amount;
}
Change your Store
class to something more like this:
public class Store {
private ArrayList<Customer> custArr;
public new Store() {
custArr = new ArrayList<Customer>();
}
public void addSale(String customerName, double amount) {
custArr.add(new Customer(customerName, amount));
}
public Customer getSaleAtIndex(int index) {
return custArr.get(index);
}
//or if you want the entire ArrayList:
public ArrayList getCustArr() {
return custArr;
}
}
If you want to have a behavior similar to JMP, creating column titles that keep all info from the multi index you can use:
newidx = []
for (n1,n2) in df.columns.ravel():
newidx.append("%s-%s" % (n1,n2))
df.columns=newidx
It will change your dataframe from:
I V
mean std first
V
4200.0 25.499536 31.557133 4200.0
4300.0 25.605662 31.678046 4300.0
4400.0 26.679005 32.919996 4400.0
4500.0 26.786458 32.811633 4500.0
to
I-mean I-std V-first
V
4200.0 25.499536 31.557133 4200.0
4300.0 25.605662 31.678046 4300.0
4400.0 26.679005 32.919996 4400.0
4500.0 26.786458 32.811633 4500.0
This example will exit after 5 seconds if another instance is already running.
// unique id for global mutex - Global prefix means it is global to the machine
const string mutex_id = "Global\\{B1E7934A-F688-417f-8FCB-65C3985E9E27}";
static void Main(string[] args)
{
using (var mutex = new Mutex(false, mutex_id))
{
try
{
try
{
if (!mutex.WaitOne(TimeSpan.FromSeconds(5), false))
{
Console.WriteLine("Another instance of this program is running");
Environment.Exit(0);
}
}
catch (AbandonedMutexException)
{
// Log the fact the mutex was abandoned in another process, it will still get aquired
}
// Perform your work here.
}
finally
{
mutex.ReleaseMutex();
}
}
}
Another Solution to isolate a character in a string
package main
import "fmt"
func main() {
var word string = "ZbjTS"
// P R I N T
fmt.Println(word)
yo := string([]rune(word)[0])
fmt.Println(yo)
//I N D E X
x :=0
for x < len(word){
yo := string([]rune(word)[x])
fmt.Println(yo)
x+=1
}
}
for string arrays also:
fmt.Println(string([]rune(sArray[0])[0]))
// = commented line
on particular computer color codes can be assigned to different RGB color by editing color values in cmd window properties. Easy click color on color palete and change their rgb values.
you need to initialize the object elements of the array.
GameObject[] houses = new GameObject[200];
for (int i=0;`i<house` i<houses.length; i++)
{ houses[i] = new GameObject();}
Of course you initialize elements selectively using different constructors anywhere else before you reference them.
The your seems a multi-array, not a JSON object.
If you want access the object like an array, you have to use some sort of key/value, such as:
var JSONObject = {
"city": ["Blankaholm, "Gamleby"],
"date": ["2012-10-23", "2012-10-22"],
"description": ["Blankaholm. Under natten har det varit inbrott", "E22 i med Gamleby. Singelolycka. En bilist har.],
"lat": ["57.586174","16.521841"],
"long": ["57.893162","16.406090"]
}
and access it with:
JSONObject.city[0] // => Blankaholm
JSONObject.date[1] // => 2012-10-22
and so on...
or
JSONObject['city'][0] // => Blankaholm
JSONObject['date'][1] // => 2012-10-22
and so on...
or, in last resort, if you don't want change your structure, you can do something like that:
var JSONObject = {
"data": [
["Blankaholm, "Gamleby"],
["2012-10-23", "2012-10-22"],
["Blankaholm. Under natten har det varit inbrott", "E22 i med Gamleby. Singelolycka. En bilist har.],
["57.586174","16.521841"],
["57.893162","16.406090"]
]
}
JSONObject.data[0][1] // => Gambleby
Use localStorage to store the fact that you opened the page :
$(document).ready(function() {
var yetVisited = localStorage['visited'];
if (!yetVisited) {
// open popup
localStorage['visited'] = "yes";
}
});
If the error is
Error: Node Sass version 5.0.0 is incompatible with ^4.0.0
Step1: stop the server
Step2: run commands are npm uninstall node-sass
Step3: check node-sass in package.json
if node-sass is available in the file then again run Step2.
Step4: npm install [email protected]
<=== run command
Step5: wait until the command successfully runs.
Step6: start-server using npm start
"Knowing about sites which handles such massive traffic gives lots of pointers for architects etc. to keep in mind certain stuff while designing new sites"
I think you can probably learn a lot from the design of Facebook, just as you can from the design of any successful large software system. However, it seems to me that you should not keep the current design of Facebook in mind when designing new systems.
Why do you want to be able to handle the traffic that Facebook has to handle? Odds are that you will never have to, no matter how talented a programmer you may be. Facebook itself was not designed from the start for such massive scalability, which is perhaps the most important lesson to learn from it.
If you want to learn about a non-trivial software system I can recommend the book "Dissecting a C# Application" about the development of the SharpDevelop IDE. It is out of print, but it is available for free online. The book gives you a glimpse into a real application and provides insights about IDEs which are useful for a programmer.
you can use this :
return redirect()->back()->withSuccess('IT WORKS!');
and use this in your view :
@if(session('success'))
<h1>{{session('success')}}</h1>
@endif
Simplest and fastest way is to replace the first char of the string by making it an upper case char:
string str = "test";<br>
str = str.Replace(str[0], char.ToUpper(str[0]));
There is also the method described in Easy way to display your apps version number using Maven:
Add this to pom.xml
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>test.App</mainClass>
<addDefaultImplementationEntries>
true
</addDefaultImplementationEntries>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
Then use this:
App.class.getPackage().getImplementationVersion()
I have found this method to be simpler.
I had this error. Nothing worked for me until I opened the SQLServer log file in the "MSSQL10_50" Log folder. That clearly stated which file could not be overwritten. It turned out that the .mdf file was being written into the "MSSQL10" data folder. I made sure that folder had the same SQLServer user permissions as the "MSSQL10_50" equivalent folder. Then it all worked.
The issue here is that the error detail is logged but not reported, so check the logs.
Stackoverflow uses such function to determine the age of a user.
The given answer is
DateTime now = DateTime.Today;
int age = now.Year - bday.Year;
if (now < bday.AddYears(age)) age--;
So your helper method would look like
public static string Age(this HtmlHelper helper, DateTime birthday)
{
DateTime now = DateTime.Today;
int age = now.Year - birthday.Year;
if (now < birthday.AddYears(age)) age--;
return age.ToString();
}
Today, I use a different version of this function to include a date of reference. This allow me to get the age of someone at a future date or in the past. This is used for our reservation system, where the age in the future is needed.
public static int GetAge(DateTime reference, DateTime birthday)
{
int age = reference.Year - birthday.Year;
if (reference < birthday.AddYears(age)) age--;
return age;
}
1-Install AjaxControl Toolkit easily by Nugget
PM> Install-Package AjaxControlToolkit
2-then in markup
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:TextBox ID="txtMovie" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" TargetControlID="txtMovie"
runat="server" />
3- in code-behind : to get the suggestions
[System.Web.Services.WebMethodAttribute(),System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] GetCompletionList(string prefixText, int count, string contextKey) {
// Create array of movies
string[] movies = {"Star Wars", "Star Trek", "Superman", "Memento", "Shrek", "Shrek II"};
// Return matching movies
return (from m in movies where m.StartsWith(prefixText,StringComparison.CurrentCultureIgnoreCase) select m).Take(count).ToArray();
}
source: http://www.asp.net/ajaxlibrary/act_autocomplete_simple.ashx
Using this shell command it will work:
SPRING_PROFILES_ACTIVE=test gradle clean bootRun
Sadly this is the simplest way I have found. It sets environment property for that call and then runs the app.
string replace() function perfectly solves this problem:
string.replace(s, old, new[, maxreplace])
Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.
>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'
Check this method after iOS 7 and later.
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewAutomaticDimension;
}
Improvements have been made to this in iOS 8. We can set it as property of the table view itself.
For me it has worked this in this order:
php artisan config:cache
php artisan config:clear
php artisan cache:clear
And I've tried all the rests without luck.
Try this code:
<form id="myform">
<!-- form elements -->
<a href="#" onclick="document.getElementById('myform').submit()">Submit</a>
</form>
But users with disabled JavaScript won't be able to submit the form, so you could add the following code:
<noscript>
<input type="submit" value="Submit form!" />
</noscript>
2020 Answer
If you want to do it in a npm script, You DON'T need to previously install any 3rd party package if you use the command npx
If for example, you want to delete the folders dist and .cache when you run npm run clean
then just add this command to your package.json
{
"scripts": {
"clean": "npx rimraf dist .cache"
}
}
It will work in any operative system
var tds = document.getElementById("ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a").getElementsByTagName("td");
time = tds[0].firstChild.value;
address = tds[3].firstChild.value;
This is pretty simple with numpy
, just subtract the arrays:
diffs = array1 - array2
I get:
diffs == array([ 0.1, 0.2, 0.3])
It stands for Representational State Transfer and it can mean a lot of things, but usually when you are talking about APIs and applications, you are talking about REST as a way to do web services or get programs to talk over the web.
REST is basically a way of communicating between systems and does much of what SOAP RPC was designed to do, but while SOAP generally makes a connection, authenticates and then does stuff over that connection, REST works pretty much the same way that that the web works. You have a URL and when you request that URL you get something back. This is where things start getting confusing because people describe the web as a the largest REST application and while this is technically correct it doesn't really help explain what it is.
In a nutshell, REST allows you to get two applications talking over the Internet using tools that are similar to what a web browser uses. This is much simpler than SOAP and a lot of what REST does is says, "Hey, things don't have to be so complex."
Worth reading:
We can add Unique key index by using fluent api. Below code worked for me
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().Property(p => p.Email).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_EmailIndex") { IsUnique = true }));
}
.outerdiv {
margin-left: auto;
margin-right: auto;
display: table;
}
Doesn't work in internet explorer 7... but who cares ?
Is there something special with that directory or are you really just asking how to copy directories?
Copy recursively via CLI:
cp -R <sourcedir> <destdir>
If you're only seeing the files under the sourcedir
being copied (instead of sourcedir
as well), that's happening because you kept the trailing slash for sourcedir
:
cp -R <sourcedir>/ <destdir>
The above only copies the files and their directories inside of sourcedir
. Typically, you want to include the directory you're copying, so drop the trailing slash:
cp -R <sourcedir> <destdir>
HTTPS proxy doesn't make sense because you can't terminate your HTTP connection at the proxy for security reasons. With your trust policy, it might work if the proxy server has a HTTPS port. Your error is caused by connecting to HTTP proxy port with HTTPS.
You can connect through a proxy using SSL tunneling (many people call that proxy) using proxy CONNECT command. However, Java doesn't support newer version of proxy tunneling. In that case, you need to handle the tunneling yourself. You can find sample code here,
http://www.javaworld.com/javaworld/javatips/jw-javatip111.html
EDIT: If you want defeat all the security measures in JSSE, you still need your own TrustManager. Something like this,
public SSLTunnelSocketFactory(String proxyhost, String proxyport){
tunnelHost = proxyhost;
tunnelPort = Integer.parseInt(proxyport);
dfactory = (SSLSocketFactory)sslContext.getSocketFactory();
}
...
connection.setSSLSocketFactory( new SSLTunnelSocketFactory( proxyHost, proxyPort ) );
connection.setDefaultHostnameVerifier( new HostnameVerifier()
{
public boolean verify( String arg0, SSLSession arg1 )
{
return true;
}
} );
EDIT 2: I just tried my program I wrote a few years ago using SSLTunnelSocketFactory and it doesn't work either. Apparently, Sun introduced a new bug sometime in Java 5. See this bug report,
http://bugs.sun.com/view_bug.do?bug_id=6614957
The good news is that the SSL tunneling bug is fixed so you can just use the default factory. I just tried with a proxy and everything works as expected. See my code,
public class SSLContextTest {
public static void main(String[] args) {
System.setProperty("https.proxyHost", "proxy.xxx.com");
System.setProperty("https.proxyPort", "8888");
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
// set up a TrustManager that trusts everything
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
System.out.println("getAcceptedIssuers =============");
return null;
}
public void checkClientTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkClientTrusted =============");
}
public void checkServerTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkServerTrusted =============");
}
} }, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(
sslContext.getSocketFactory());
HttpsURLConnection
.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String arg0, SSLSession arg1) {
System.out.println("hostnameVerifier =============");
return true;
}
});
URL url = new URL("https://www.verisign.net");
URLConnection conn = url.openConnection();
BufferedReader reader =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is what I get when I run the program,
checkServerTrusted =============
hostnameVerifier =============
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
......
As you can see, both SSLContext and hostnameVerifier are getting called. HostnameVerifier is only involved when the hostname doesn't match the cert. I used "www.verisign.net" to trigger this.
Any comments on this one?
...
doShow = function(){
if($('#img_id').attr('complete')){
alert('Image is loaded!');
} else {
window.setTimeout('doShow()',100);
}
};
$('#img_id').attr('src','image.jpg');
doShow();
...
Seems like works everywhere...
Try -Wno-traditional
.
But better, add declarations for your static functions:
static void foo (void);
// ... somewhere in code
foo ();
static void foo ()
{
// do sth
}
The content of the Manifest file in a JAR file created with version 1.0 of the Java Development Kit is the following.
Manifest-Version: 1.0
All the entries are as name-value pairs. The name of a header is separated from its value by a colon. The default manifest shows that it conforms to version 1.0 of the manifest specification. The manifest can also contain information about the other files that are packaged in the archive. Exactly what file information is recorded in the manifest will depend on the intended use for the JAR file. The default manifest file makes no assumptions about what information it should record about other files, so its single line contains data only about itself. Special-Purpose Manifest Headers
Depending on the intended role of the JAR file, the default manifest may have to be modified. If the JAR file is created only for the purpose of archival, then the MANIFEST.MF file is of no purpose. Most uses of JAR files go beyond simple archiving and compression and require special information to be in the manifest file. Summarized below are brief descriptions of the headers that are required for some special-purpose JAR-file functions
Applications Bundled as JAR Files: If an application is bundled in a JAR file, the Java Virtual Machine needs to be told what the entry point to the application is. An entry point is any class with a public static void main(String[] args) method. This information is provided in the Main-Class header, which has the general form:
Main-Class: classname
The value classname is to be replaced with the application's entry point.
Download Extensions: Download extensions are JAR files that are referenced by the manifest files of other JAR files. In a typical situation, an applet will be bundled in a JAR file whose manifest references a JAR file (or several JAR files) that will serve as an extension for the purposes of that applet. Extensions may reference each other in the same way. Download extensions are specified in the Class-Path header field in the manifest file of an applet, application, or another extension. A Class-Path header might look like this, for example:
Class-Path: servlet.jar infobus.jar acme/beans.jar
With this header, the classes in the files servlet.jar, infobus.jar, and acme/beans.jar will serve as extensions for purposes of the applet or application. The URLs in the Class-Path header are given relative to the URL of the JAR file of the applet or application.
Package Sealing: A package within a JAR file can be optionally sealed, which means that all classes defined in that package must be archived in the same JAR file. A package might be sealed to ensure version consistency among the classes in your software or as a security measure. To seal a package, a Name header needs to be added for the package, followed by a Sealed header, similar to this:
Name: myCompany/myPackage/
Sealed: true
The Name header's value is the package's relative pathname. Note that it ends with a '/' to distinguish it from a filename. Any headers following a Name header, without any intervening blank lines, apply to the file or package specified in the Name header. In the above example, because the Sealed header occurs after the Name: myCompany/myPackage header, with no blank lines between, the Sealed header will be interpreted as applying (only) to the package myCompany/myPackage.
Package Versioning: The Package Versioning specification defines several manifest headers to hold versioning information. One set of such headers can be assigned to each package. The versioning headers should appear directly beneath the Name header for the package. This example shows all the versioning headers:
Name: java/util/
Specification-Title: "Java Utility Classes"
Specification-Version: "1.2"
Specification-Vendor: "Sun Microsystems, Inc.".
Implementation-Title: "java.util"
Implementation-Version: "build57"
Implementation-Vendor: "Sun Microsystems, Inc."
There is a way to catch the error directly in the except clause with ConnectionResetError, better to isolate the right error. This example also catches the timeout.
from urllib.request import urlopen
from socket import timeout
url = "http://......"
try:
string = urlopen(url, timeout=5).read()
except ConnectionResetError:
print("==> ConnectionResetError")
pass
except timeout:
print("==> Timeout")
pass
import re
word = 'fubar'
regexp = re.compile(r'ba[rzd]')
if regexp.search(word):
print 'matched'
The error is because you are including the script links at two places which will do the override and re-initialization of date-picker
<meta charset="utf-8">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />_x000D_
_x000D_
_x000D_
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>_x000D_
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>_x000D_
_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
$('.dateinput').datepicker({ format: "yyyy/mm/dd" });_x000D_
}); _x000D_
</script>_x000D_
_x000D_
<!-- Bootstrap core JavaScript_x000D_
================================================== -->_x000D_
<!-- Placed at the end of the document so the pages load faster -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
_x000D_
So exclude either src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"
or src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"
It will work..
I think you've got one major problem here: there's no monotonically increasing "counter" to guarantee that a given row has happened later in time than another. Take this example:
timestamp lives_remaining user_id trans_id
10:00 4 3 5
10:00 5 3 6
10:00 3 3 1
10:00 2 3 2
You cannot determine from this data which is the most recent entry. Is it the second one or the last one? There is no sort or max() function you can apply to any of this data to give you the correct answer.
Increasing the resolution of the timestamp would be a huge help. Since the database engine serializes requests, with sufficient resolution you can guarantee that no two timestamps will be the same.
Alternatively, use a trans_id that won't roll over for a very, very long time. Having a trans_id that rolls over means you can't tell (for the same timestamp) whether trans_id 6 is more recent than trans_id 1 unless you do some complicated math.
Give it as "C:\Program Files\Java\jdk1.6.0_16\bin". Remove the backslash it will work
protected void grdDataListeDetay_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[3].Text != "0")
{
for (int i = 0; i <= e.Row.Cells.Count - 1; i++)
{
e.Row.Cells[i].BackColor = System.Drawing.Color.Beige;
}
}
}
}
Solomon's answer about bootstrap inspired me to add the CSS the bootstrap solution uses, which works really well for me.
.iframe-embed {
position: absolute;
top: 0;
left: 0;
bottom: 0;
height: 100%;
width: 100%;
border: 0;
}
.iframe-embed-wrapper {
position: relative;
display: block;
height: 0;
padding: 0;
overflow: hidden;
}
.iframe-embed-responsive-16by9 {
padding-bottom: 56.25%;
}
<div class="iframe-embed-wrapper iframe-embed-responsive-16by9">
<iframe class="iframe-embed" src="vid.mp4"></iframe>
</div>
Use option bty = "n"
in legend
to remove the box around the legend. For example:
legend(1, 5,
"This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",
bty = "n")
This copies the 5 cells to the right of the activecell. If you have a range selected, the active cell is the top left cell in the range.
Sub Copy5CellsToRight()
ActiveCell.Offset(, 1).Resize(1, 5).Copy
End Sub
If you want to include the activecell in the range that gets copied, you don't need the offset:
Sub ExtendAndCopy5CellsToRight()
ActiveCell.Resize(1, 6).Copy
End Sub
Note that you don't need to select before copying.
I have an Entity Framework web application that works on my local machine, but this error appears when pushed to another environment. There are other non-Entity Framework applications that work, and I'm able to connect with sqlplus.
Using sysinternals Process Monitor shows that tns names file is not being loaded correctly:
Following the documentation I tried to add a section giving the location of the tnsnames file like so:
<configuration>
<configSections>
<section name="oracle.manageddataaccess.client"
type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/>
</configSections>
<oracle.manageddataaccess.client>
<version number="*">
<settings>
<setting name="TNS_ADMIN" value="C:\Oracle\product\12.1.0\client_1\Network\Admin"/>
</settings>
</version>
</oracle.manageddataaccess.client>
<configuration>
However, this resulted in an immediate 500 server error.
Further investigation showed that the dll I was packaging with the web application was version 4.122.1.0, while the Oracle client environment installed on the machine was 4.121.2.0. As explained in the Oracle EntityFramework package documentation
Note: If your application is a web application and the above entry was added to a web.config and the same config section handler for "oracle.manageddataaccess.client" also exists in machine.config but the "Version" attribute values are different, an error message of "There is a duplicate 'oracle.manageddataaccess.client' section defined." may be observed at runtime. If so, the config section handler entry in the machine.config for "oracle.manageddataaccess.client" has to be removed from the machine.config for the web application to not encounter this error. But given that there may be other applications on the machine that depended on this entry in the machine.config, this config section handler entry may need to be moved to all of the application's .NET config file on that machine that depend on it.
I attempted to add a separate version section in the .NET machine.config without success (there existed a section for version 4.121.2.0 and I added a section for version 4.122.1.0). After I removed the "oracle.manageddataaccess.client" section from the machine.config, the above addition to the web.config resolved ORA-12154.
While researching this problem I found that the TNS_ADMIN environmental variable was not set. I created a new environmental variable called TNS_ADMIN and set the value to "C:\Oracle\product\12.1.0\client_1\Network\Admin". I removed the web.config changes, and removed the "oracle.manageddataaccess.client" section from .NET machine.config, but still received ORA-12154. Only after I restarted the machine did this resolve the issue.
I added an entry for the correct version in the registry and this resolved the issue:
HKLM\Software\Wow6432Node\Oracle\ODP.NET.Managed\4.121.2.0
The name of the key is TNS_ADMIN
and this points to the folder containing the tnsnames file:
C:\Oracle\product\12.1.0\client_1\network
Not the C:\Oracle\product\12.1.0\client_1\network\admin
folder.
ALTER TABLE Protocols
ADD ProtocolTypeID int NOT NULL DEFAULT(1)
GO
The inclusion of the DEFAULT fills the column in existing rows with the default value, so the NOT NULL constraint is not violated.
The "error_page" parameter makes a redirect, converting the request method to "GET", it is not a custom response page.
The easiest solution is
server{
root /var/www/html;
location ~ \.php {
if (!-f $document_root/$fastcgi_script_name){
return 404;
}
fastcgi_pass 127.0.0.1:9000;
include fastcgi_params.default;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
}
By the way, if you want Nginx to process 404 status returned by PHP scripts, you need to add
[fastcgi_intercept_errors][1] on;
E.g.
location ~ \.php {
#...
error_page 404 404.html;
fastcgi_intercept_errors on;
}
If you actually have set a root password and you've just lost/forgotten it:
Restart it manually with the skip-grant-tables option: mysqld_safe --skip-grant-tables
Now, open a new terminal window and run the MySQL client: mysql -u root
Reset the root password manually with this MySQL command: UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root';
If you are using MySQL 5.7 (check using mysql --version in the Terminal) then the command is:
UPDATE mysql.user SET authentication_string=PASSWORD('password') WHERE User='root';
Flush the privileges with this MySQL command: FLUSH PRIVILEGES;
From http://www.tech-faq.com/reset-mysql-password.shtml
(Maybe this isn't what you need, Abs, but I figure it could be useful for people stumbling across this question in the future)
mainJSON.getJSONArray("source")
returns a JSONArray
, hence you can remove the new JSONArray.
The JSONArray contructor with an object parameter expects it to be a Collection or Array (not JSONArray)
Try this:
JSONArray jsonMainArr = mainJSON.getJSONArray("source");
Go to the project "Properties" => "Web", and on the "Servers" section change the port to something else that is not used in and save it. You will be asked to created a virtual directory and click "Yes". Now run the project and it will work now.
I prefer to use
pushd d:\windows\movie
because it requires no switches yet the working directory will change to the correct drive and path in one step.
Added plus:
popd
. var str = "I expect five hundred dollars ($500) ($1).";
var rex = /\$\d+(?=\))/;
alert(rex.exec(str));
Will match the first number starting with a $ and followed by ')'. ')' will not be part of the match. The code alerts with the first match.
var str = "I expect five hundred dollars ($500) ($1).";
var rex = /\$\d+(?=\))/g;
var matches = str.match(rex);
for (var i = 0; i < matches.length; i++)
{
alert(matches[i]);
}
This code alerts with all the matches.
References:
search for "?=n" http://www.w3schools.com/jsref/jsref_obj_regexp.asp
search for "x(?=y)" https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Here's the one that is working for me.
from datetime import datetime
date_format = "%H:%M:%S"
# You could also pass datetime.time object in this part and convert it to string.
time_start = str('09:00:00')
time_end = str('18:00:00')
# Then get the difference here.
diff = datetime.strptime(time_end, date_format) - datetime.strptime(time_start, date_format)
# Get the time in hours i.e. 9.60, 8.5
result = diff.seconds / 3600;
Hope this helps!
let date = Date()
let units: Set<Calendar.Component> = [.hour, .day, .month, .year]
let comps = Calendar.current.dateComponents(units, from: date)
I would prefer the C++ size constraints over the C versions:
// Ignore to the end of file
cin.ignore(std::numeric_limits<std::streamsize>::max())
// Ignore to the end of line
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
Open notepad and paste this code:
@echo off
powershell -Command "Start-Process cmd -Verb RunAs -ArgumentList '/c cd /d %CD% && %*'"
@echo on
Then, save the file as sudo.cmd
. Copy this file and paste it at C:\Windows\System32
or add the path where sudo.cmd
is to your PATH Environment Variable.
When you open command prompt, you can now run something like sudo start .
.
If you want the admin command prompt window to stay open when you run the command, change the code in notepad to this:
@echo off
powershell -Command "Start-Process cmd -Verb RunAs -ArgumentList '/k cd /d %CD% && %*'"
@echo on
Explanation:
powershell -Command
runs a powershell command.
Start-Process
is a powershell command that starts a process, in this case, command prompt.
-Verb RunAs
runs the command as admin.
-Argument-List
runs the command with arguments.
Our arguments are '/c cd /d %CD% && %*'
. %*
means all arguments, so if you did sudo foo bar
, it would run in command prompt foo bar
because the parameters are foo and bar, and %*
returns foo bar
. cd /d %CD%
is a command to go to the current directory. This will ensure that when you open the elevated window, the directory will be the same as the normal window. the &&
means that if the first command is successful, run the second command.
The /c
is a cmd parameter for closing the window after the command is finished, and the /k
is a cmd parameter for keeping the window open.
Credit to Adam Plocher for the staying in the current directory code.
In Kotlin you can use substringAfterLast
, specifying a delimiter.
val string = "/abc/def/ghfj.doc"
val result = url.substringAfterLast("/")
println(result)
// It will show ghfj.doc
From the doc:
Returns a substring after the last occurrence of delimiter. If the string does not contain the delimiter, returns missingDelimiterValue which defaults to the original string.
The results will completely depend on the browser, to give an objective verdict, we have to make some performance tests, here are some results, you can run them here:
Chrome 6:
Firefox 3.6:
Firefox 4.0b2:
Safari 5:
IE9 Platform Preview 3:
Don't add the bcc header.
See this: http://mail.python.org/pipermail/email-sig/2004-September/000151.html
And this: """Notice that the second argument to sendmail(), the recipients, is passed as a list. You can include any number of addresses in the list to have the message delivered to each of them in turn. Since the envelope information is separate from the message headers, you can even BCC someone by including them in the method argument but not in the message header.""" from http://pymotw.com/2/smtplib
toaddr = '[email protected]'
cc = ['[email protected]','[email protected]']
bcc = ['[email protected]']
fromaddr = '[email protected]'
message_subject = "disturbance in sector 7"
message_text = "Three are dead in an attack in the sewers below sector 7."
message = "From: %s\r\n" % fromaddr
+ "To: %s\r\n" % toaddr
+ "CC: %s\r\n" % ",".join(cc)
# don't add this, otherwise "to and cc" receivers will know who are the bcc receivers
# + "BCC: %s\r\n" % ",".join(bcc)
+ "Subject: %s\r\n" % message_subject
+ "\r\n"
+ message_text
toaddrs = [toaddr] + cc + bcc
server = smtplib.SMTP('smtp.sunnydale.k12.ca.us')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, message)
server.quit()
The FileInputStream
class works directly with the underlying file system. If the file in question is not physically present there, it will fail to open it. The getResourceAsStream()
method works differently. It tries to locate and load the resource using the ClassLoader
of the class it is called on. This enables it to find, for example, resources embedded into jar
files.
I've been stuck with the same issue, and the preceding answer did not help me (albeit well written).
The solution is here : check your /etc/redis/redis.conf
, and make sure to change the default
bind 127.0.0.1
to
bind 0.0.0.0
Then restart your service (service redis-server restart
)
You can then now check that redis is listening on non-local interface with
redis-cli -h 192.168.x.x ping
(replace 192.168.x.x with your IP adress)
Important note : as several users stated, it is not safe to set this on a server which is exposed to the Internet. You should be certain that you redis is protected with any means that fits your needs.
Your example:
{
"items":
[
{
"WR":"qwe",
"QU":"asd",
"QA":"end",
"WO":"hasd",
"NO":"qwer"
},
...
]
}
add an element "itemorder"
{
"items":
[
{
"WR":"qwe",
"QU":"asd",
"QA":"end",
"WO":"hasd",
"NO":"qwer"
},
...
],
"itemorder":["WR","QU","QA","WO","NO"]
}
This code generates the desired output without the column title line:
JSONObject output = new JSONObject(json);
JSONArray docs = output.getJSONArray("data");
JSONArray names = output.getJSONArray("itemOrder");
String csv = CDL.toString(names,docs);
jQuery can handle JSONP, just pass an url formatted with the callback=? parameter to the $.getJSON
method, for example:
$.getJSON("https://api.ipify.org/?format=json", function(e) {_x000D_
console.log(e.ip);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
This example is of a really simple JSONP service implemented on with api.ipify.org
.
If you aren't looking for a cross-domain solution the script can be simplified even more, since you don't need the callback parameter, and you return pure JSON.
SELECT *
FROM TABLE A
WHERE NOT EXISTS (SELECT 'X'
FROM TABLE B
WHERE B.KEYFIELD1 = A.KEYFIELD1
AND B.KEYFIELD2 = A.KEYFIELD2
AND B.KEYFIELD3 = A.KEYFIELD3)
;
'X' is any value.
Switch the tables to see the different discrepancies.
Make sure to join the key fields in your tables.
Or just use the MINUS operator with 2 select statements, however, MINUS can only work in Oracle.
This https://stackoverflow.com/a/13266763/1277458 works perfectly. But if you have 64-bit operation system use Framework64 instead of Framework in path:
c:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
I found this gem from Flysystem
spl_autoload_register(function($class) {
$prefix = 'League\\Flysystem\\';
if ( ! substr($class, 0, 17) === $prefix) {
return;
}
$class = substr($class, strlen($prefix));
$location = __DIR__ . 'path/to/flysystem/src/' . str_replace('\\', '/', $class) . '.php';
if (is_file($location)) {
require_once($location);
}
});
Check your file: settings.gradle
for presence lines with included subprojects (for example:
include chapter1-bookstore
)
Expanding on Sjoerd's anti-join, you can also use the easy to understand SELECT WHERE X NOT IN (SELECT)
pattern.
SELECT pm.id FROM r2r.partmaster pm
WHERE pm.id NOT IN (SELECT pd.part_num FROM wpsapi4.product_details pd)
Note that you only need to use `
backticks on reserved words, names with spaces and such, not with normal column names.
On MySQL 5+ this kind of query runs pretty fast.
On MySQL 3/4 it's slow.
Make sure you have indexes on the fields in question
You need to have an index on pm.id
, pd.part_num
.
Basing off of m59's very good answer. I found that model inputs would be blurred if they changed, so you could only change one character at a time. This is a new one for lists of objects for anyone that needs it:
EDIT Updated to handle multiple filters on one page
app.filter('partition', function() {
var cache = {}; // holds old arrays for difference repeat scopes
var filter = function(newArr, size, scope) {
var i,
oldLength = 0,
newLength = 0,
arr = [],
id = scope.$id,
currentArr = cache[id];
if (!newArr) return;
if (currentArr) {
for (i = 0; i < currentArr.length; i++) {
oldLength += currentArr[i].length;
}
}
if (newArr.length == oldLength) {
return currentArr; // so we keep the old object and prevent rebuild (it blurs inputs)
} else {
for (i = 0; i < newArr.length; i += size) {
arr.push(newArr.slice(i, i + size));
}
cache[id] = arr;
return arr;
}
};
return filter;
});
And this would be the usage:
<div ng-repeat="row in items | partition:3:this">
<span class="span4">
{{ $index }}
</span>
</div>
this really worked form for I am making a table using thymeleaf and inside the table there is two buttons in one form...thanks man even this thread is old it still helps me alot!
<th:block th:each="infos : ${infos}">_x000D_
<tr>_x000D_
<form method="POST">_x000D_
<td><input class="admin" type="text" name="firstName" id="firstName" th:value="${infos.firstName}"/></td>_x000D_
<td><input class="admin" type="text" name="lastName" id="lastName" th:value="${infos.lastName}"/></td>_x000D_
<td><input class="admin" type="email" name="email" id="email" th:value="${infos.email}"/></td>_x000D_
<td><input class="admin" type="text" name="passWord" id="passWord" th:value="${infos.passWord}"/></td>_x000D_
<td><input class="admin" type="date" name="birthDate" id="birthDate" th:value="${infos.birthDate}"/></td>_x000D_
<td>_x000D_
<select class="admin" name="gender" id="gender">_x000D_
<option><label th:text="${infos.gender}"></label></option>_x000D_
<option value="Male">Male</option>_x000D_
<option value="Female">Female</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="status" id="status">_x000D_
<option><label th:text="${infos.status}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="ustatus" id="ustatus">_x000D_
<option><label th:text="${infos.ustatus}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="type" id="type">_x000D_
<option><label th:text="${infos.type}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select></td>_x000D_
<td><input class="register" id="mobileNumber" type="text" th:value="${infos.mobileNumber}" name="mobileNumber" onkeypress="return isNumberKey(event)" maxlength="11"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Upd" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/updates}"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Del" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/delete}"/></td>_x000D_
</form>_x000D_
</tr>_x000D_
</th:block>
_x000D_
You can use Ctrl+Shift+Down+D to add the formula to every cell in the column as well.
Simply click/highlight the cell with the equation/formula you want to copy and then hold down Ctrl+Shift+Down+D and your formula will be added to each cell.
in the example below I exclude
spring-boot-starter-tomcat
compile("org.springframework.boot:spring-boot-starter-web") {
//by both name and group
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
}
Using the example data set that Ananda dummied up, here's an example using aggregate()
, which is part of core R. aggregate()
just needs something to count as function of the different values of MONTH-YEAR
. In this case, I used VALUE
as the thing to count:
aggregate(cbind(count = VALUE) ~ MONTH.YEAR,
data = mydf,
FUN = function(x){NROW(x)})
which gives you..
MONTH.YEAR count
1 FEB. 2012 2
2 JAN. 2012 2
3 MAR. 2012 1
For a solution without jQuery check out Visibility.js which provides information about three page states
visible ... page is visible
hidden ... page is not visible
prerender ... page is being prerendered by the browser
and also convenience-wrappers for setInterval
/* Perform action every second if visible */
Visibility.every(1000, function () {
action();
});
/* Perform action every second if visible, every 60 sec if not visible */
Visibility.every(1000, 60*1000, function () {
action();
});
A fallback for older browsers (IE < 10; iOS < 7) is also available
Try,
var newList =
(
from x in empCollection
select new {Loc = x.empLoc, PL = x.empPL, Shift = x.empShift}
).Distinct();
Use child.setLocation(0, 0)
on the button, and parent.setLayout(null)
. Instead of using setBounds(...) on the JFrame to size it, consider using just setSize(...)
and letting the OS position the frame.
//JPanel
JPanel pnlButton = new JPanel();
//Buttons
JButton btnAddFlight = new JButton("Add Flight");
public Control() {
//JFrame layout
this.setLayout(null);
//JPanel layout
pnlButton.setLayout(null);
//Adding to JFrame
pnlButton.add(btnAddFlight);
add(pnlButton);
// postioning
pnlButton.setLocation(0,0);
You can't do it with just CSS, but you can do it with Javascript, and (optionally) jQuery.
If you want to do it without jQuery:
<script>
window.onload = function() {
var anchors = document.getElementsByTagName('a');
for(var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
anchor.onclick = function() {
alert('ho ho ho');
}
}
}
</script>
And to do it without jQuery, and only on a specific class (ex: hohoho
):
<script>
window.onload = function() {
var anchors = document.getElementsByTagName('a');
for(var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
if(/\bhohoho\b/).match(anchor.className)) {
anchor.onclick = function() {
alert('ho ho ho');
}
}
}
}
</script>
If you are okay with using jQuery, then you can do this for all anchors:
<script>
$(document).ready(function() {
$('a').click(function() {
alert('ho ho ho');
});
});
</script>
And this jQuery snippet to only apply it to anchors with a specific class:
<script>
$(document).ready(function() {
$('a.hohoho').click(function() {
alert('ho ho ho');
});
});
</script>
Not really recommended but none of the other answers are really global variables. For a truly global variable you could do this.
<body>
<app-root></app-root>
<script>
myTest = 1;
</script>
</body>
..near the top right after imports:
declare const myTest: any;
...later:
console.warn(myTest); // outputs '1'
Use:
import copy
def ndlist(*args, init=0):
dp = init
for x in reversed(args):
dp = [copy.deepcopy(dp) for _ in range(x)]
return dp
l = ndlist(1,2,3,4) # 4 dimensional list initialized with 0's
l[0][1][2][3] = 1
I do think NumPy is the way to go. The above is a generic one if you don't want to use NumPy.
Get Date::Manip from CPAN, then:
use Date::Manip;
$string = '18-Sep-2008 20:09'; # or a wide range of other date formats
$unix_time = UnixDate( ParseDate($string), "%s" );
edit:
Date::Manip is big and slow, but very flexible in parsing, and it's pure perl. Use it if you're in a hurry when you're writing code, and you know you won't be in a hurry when you're running it.
e.g. Use it to parse command line options once on start-up, but don't use it parsing large amounts of data on a busy web server.
See the authors comments.
(Thanks to the author of the first comment below)
In case anyone has this problem, I had a similar problem to qix, but more nuanced.
New shell terminals would default to a different version of node. I would change my terminal to the node I wanted, but when the bundle script run, it ran in a new shell, and it got the default version which did not have react-native installed.
I used nvm alias default x.x.x
so that new shells would inherit the default version I wanted.
To handle eliminating duplicates, implement an IEqualityComparer<Person>
that can be used in the Distinct()
method, and then getting your dictionary will be easy.
Given:
class PersonComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
return x.FirstAndLastName.Equals(y.FirstAndLastName, StringComparison.OrdinalIgnoreCase);
}
public int GetHashCode(Person obj)
{
return obj.FirstAndLastName.ToUpper().GetHashCode();
}
}
class Person
{
public string FirstAndLastName { get; set; }
}
Get your dictionary:
List<Person> people = new List<Person>()
{
new Person() { FirstAndLastName = "Bob Sanders" },
new Person() { FirstAndLastName = "Bob Sanders" },
new Person() { FirstAndLastName = "Jane Thomas" }
};
Dictionary<string, Person> dictionary =
people.Distinct(new PersonComparer()).ToDictionary(p => p.FirstAndLastName, p => p);
If you're using the HTML5 Fetch API to make POST requests as a logged in user and getting Forbidden (CSRF cookie not set.)
, it could be because by default fetch
does not include session cookies, resulting in Django thinking you're a different user than the one who loaded the page.
You can include the session token by passing the option credentials: 'include'
to fetch:
var csrftoken = getCookie('csrftoken');
var headers = new Headers();
headers.append('X-CSRFToken', csrftoken);
fetch('/api/upload', {
method: 'POST',
body: payload,
headers: headers,
credentials: 'include'
})
You have to give width:100%
to parent to center
the text.
.parent {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
position: absolute;_x000D_
width:100%_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child">text</div>_x000D_
</div>
_x000D_
If you also need to centre align vertically, give height:100%
and align-itens: center
.parent {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
width:100%;
height: 100%;
}
Async HTTP client loopj vs. Volley
The specifics of my project are small HTTP REST requests, every 1-5 minutes.
I using an async HTTP client (1.4.1) for a long time. The performance is better than using the vanilla Apache httpClient or an HTTP URL connection. Anyway, the new version of the library is not working for me: library inter exception cut chain of callbacks.
Reading all answers motivated me to try something new. I have chosen the Volley HTTP library.
After using it for some time, even without tests, I see clearly that the response time is down to 1.5x, 2x Volley.
Maybe Retrofit is better than an async HTTP client? I need to try it. But I'm sure that Volley is not for me.
Probably distro-proof path is adding this to your .bashrc or .zshrc, whatever your shell is :
PATH="$(ruby -e 'print Gem.default_dir')/bin:$PATH"
or if you have installed your gems user-wide, use :
PATH="$(ruby -e 'print Gem.user_dir')/bin:$PATH"
Basic ideas to distinguish between those two.
Session:
Cookies:
Session is preferred when you need to store short-term information/values, such as variables for calculating, measuring, querying etc.
Cookies is preferred when you need to store long-term information/values, such as user's account (so that even when they shutdown the computer for 2 days, their account will still be logged in). I can't think of many examples for cookies since it isn't adopted in most of the situations.
For completeness:
>>> def divide(x, y):
... try:
... result = x / y
... except ZeroDivisionError:
... print("division by zero!")
... else:
... print("result is", result)
... finally:
... print("executing finally clause")
Also note that you can capture the exception like this:
>>> try:
... this_fails()
... except ZeroDivisionError as err:
... print("Handling run-time error:", err)
...and re-raise the exception like this:
>>> try:
... raise NameError('HiThere')
... except NameError:
... print('An exception flew by!')
... raise
...examples from the python tutorial.
To see a list of the Eclipse release name and it's corresponding version number go to this website. http://en.wikipedia.org/wiki/Eclipse_%28software%29#Release
I too dislike the way that the Eclipse foundation DOES NOT use the version number for their downloads or on the Help -> About Eclipse dialog. They do display the version on the download webpage, but the actual file name is something like:
But over time, you forget what release name goes with what version number. I would much prefer a file naming convention like:
This way you get BOTH from the file name and it is sortable in a directory listing. Fortunately, they mostly choose names are alphabetically after the previous one (except for 3.4-Ganymede vs the newer 3.5-Galileo).
Use something like this in case you also want to output products details per date as JSON and the MySQL
version does not support JSON
functions.
SELECT `date`,
CONCAT('{',GROUP_CONCAT('{\"id\": \"',`product_id`,'\",\"name\": \"',`product_name`,'\"}'),'}') as `productsJSON`
FROM `buy` group by `date`
order by `date` DESC
product_id product_name date
| 1 | azd | 2011-12-12 |
| 2 | xyz | 2011-12-12 |
| 3 | ase | 2011-12-11 |
| 4 | azwed | 2011-12-11 |
| 5 | wed | 2011-12-10 |
| 6 | cvg | 2011-12-10 |
| 7 | cvig | 2011-12-09 |
RESULT
date productsJSON
2011-12-12T00:00:00Z {{"id": "1","name": "azd"},{"id": "2","name": "xyz"}}
2011-12-11T00:00:00Z {{"id": "3","name": "ase"},{"id": "4","name": "azwed"}}
2011-12-10T00:00:00Z {{"id": "5","name": "wed"},{"id": "6","name": "cvg"}}
2011-12-09T00:00:00Z {{"id": "7","name": "cvig"}}
Try it out in SQL Fiddle
If you are using a MySQL
version that supports JSON
functions then the above query could be re-written:
SELECT `date`,JSON_OBJECTAGG(CONCAT('product-',`product_id`),JSON_OBJECT('id', `product_id`, 'name', `product_name`)) as `productsJSON`
FROM `buy` group by `date`
order by `date` DESC;
Try both in DB Fiddle
I found the following as the simplest method:
Here, add this line to .zshrc
:
export PATH=/home/david/pear/bin:$PATH
EDIT: This does work, but ony's answer below is better, as it takes advantage of the structured interface ZSH provides for variables like $PATH
. This approach is standard for bash
, but as far as I know, there is no reason to use it when ZSH provides better alternatives.
On OS X you want to use ~/.bash_profile. This is because by default Terminal.app opens a login shell for each new window.
See more about the different configuration files and when they are used here: What's the difference between .bashrc, .bash_profile, and .environment?
and in relation to OSX here: About .bash_profile, .bashrc, and where should alias be written in?
You could do:
chcon -R -t httpd_sys_rw_content_t storage
( SELECT * FROM table1
EXCEPT
SELECT * FROM table2)
UNION ALL
( SELECT * FROM table2
EXCEPT
SELECT * FROM table1)
Just for posterity, here's the text from several external sources regarding the Excel file formats. Some of these have been mentioned in other answers to this question but without reproducing the essential content.
1. From Doug Mahugh, August 22, 2006:
...the new XLSB binary format. Like Open XML, it’s a full-fidelity file format that can store anything you can create in Excel, but the XLSB format is optimized for performance in ways that aren’t possible with a pure XML format.
The XLSB format (also sometimes referred to as BIFF12, as in “binary file format for Office 12”) uses the same Open Packaging Convention used by the Open XML formats and XPS. So it’s basically a ZIP container, and you can open it with any ZIP tool to see what’s inside. But instead of .XML parts within the package, you’ll find .BIN parts...
This article also refers to documentation about the BIN format, too lengthy to reproduce here.
2. From MSDN Archive, August 29, 2006 which in turn cites an already-missing blog post regarding the XLSB format:
Even though we’ve done a lot of work to make sure that our XML formats open quickly and efficiently, this binary format is still more efficient for Excel to open and save, and can lead to some performance improvements for workbooks that contain a lot of data, or that would require a lot of XML parsing during the Open process. (In fact, we’ve found that the new binary format is faster than the old XLS format in many cases.) Also, there is no macro-free version of this file format – all XLSB files can contain macros (VBA and XLM). In all other respects, it is functionally equivalent to the XML file format above:
File size – file size of both formats is approximately the same, since both formats are saved to disk using zip compression Architecture – both formats use the same packaging structure, and both have the same part-level structures. Feature support – both formats support exactly the same feature set Runtime performance – once loaded into memory, the file format has no effect on application/calculation speed Converters – both formats will have identical converter support
public String datePicker(String object,String data){
APP_LOGS.debug("selecting date");
try{
WebElement dateWidget = driver.findElement(By.xpath(OR.getProperty(object)));
List<WebElement> rows = dateWidget.findElements(By.tagName("tr"));
List<WebElement> columns = dateWidget.findElements(By.tagName("td"));
for (WebElement cell: columns){
if (cell.getText().equals(data)){
cell.findElement(By.linkText(data)).click();
break;
}
}
}catch(Exception e){
return Constants.KEYWORD_FAIL+" -- Not able to select the date"+e.getMessage();
}
return Constants.KEYWORD_PASS;
}
Try this:
var newArr = [];
$.each(JSONObject.results.bindings, function(i, obj) {
newArr.push([obj.value]);
});
I found problems with the elements being moved around using some of the above, so if you have objects next to each other that you want to just swap this worked best for me
document.getElementById('uncheckAll').hidden = false;
document.getElementById('checkAll').hidden = true;
This might be off-topic. But for the wget in for loop, you can certainly do
curl -O http://example.com/search/link[1-600]
//A custom toast class where you can show custom or default toast as desired)
public class ToastMessage {
private Context context;
private static ToastMessage instance;
/**
* @param context
*/
private ToastMessage(Context context) {
this.context = context;
}
/**
* @param context
* @return
*/
public synchronized static ToastMessage getInstance(Context context) {
if (instance == null) {
instance = new ToastMessage(context);
}
return instance;
}
/**
* @param message
*/
public void showLongMessage(String message) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
/**
* @param message
*/
public void showSmallMessage(String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
/**
* The Toast displayed via this method will display it for short period of time
*
* @param message
*/
public void showLongCustomToast(String message) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(R.id.ll_toast));
TextView msgTv = (TextView) layout.findViewById(R.id.tv_msg);
msgTv.setText(message);
Toast toast = new Toast(context);
toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
/**
* The toast displayed by this class will display it for long period of time
*
* @param message
*/
public void showSmallCustomToast(String message) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(R.id.ll_toast));
TextView msgTv = (TextView) layout.findViewById(R.id.tv_msg);
msgTv.setText(message);
Toast toast = new Toast(context);
toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
}
}
Here is a simple way to do it using plain JavaScript. This is the vanilla equivalent of the jQuery script posted by pimvdb. You can test it here.
<script type='text/javascript'>
window.onload = function(){
document.getElementById('id_here').selectedIndex = -1;
}
</script>
.
<select id="id_here">
<option>aaaa</option>
<option>bbbb</option>
</select>
Make sure the "id_here" matches in the form and in the JavaScript.
use mingw32-make instead of cmake in windows
There are a couple generic types in .Net (v2 and later) that make passing functions around as delegates very easy.
For functions with return types, there is Func<> and for functions without return types there is Action<>.
Both Func and Action can be declared to take from 0 to 4 parameters. For example, Func < double, int > takes one double as a parameter and returns an int. Action < double, double, double > takes three doubles as parameters and returns nothing (void).
So you can declare your Diff function to take a Func:
public double Diff(double x, Func<double, double> f) {
double h = 0.0000001;
return (f(x + h) - f(x)) / h;
}
And then you call it as so, simply giving it the name of the function that fits the signature of your Func or Action:
double result = Diff(myValue, Function);
You can even write the function in-line with lambda syntax:
double result = Diff(myValue, d => Math.Sqrt(d * 3.14));
I know it's a late answer but I had the same problem and my solution was just adding implementation 'com.android.support:design:28.0.0
or any above support design libraries !!
// helper class, so we don't have to do a whole lot of autoboxing
private static class Count {
public int count = 0;
}
public boolean haveSameElements(final List<String> list1, final List<String> list2) {
// (list1, list1) is always true
if (list1 == list2) return true;
// If either list is null, or the lengths are not equal, they can't possibly match
if (list1 == null || list2 == null || list1.size() != list2.size())
return false;
// (switch the two checks above if (null, null) should return false)
Map<String, Count> counts = new HashMap<>();
// Count the items in list1
for (String item : list1) {
if (!counts.containsKey(item)) counts.put(item, new Count());
counts.get(item).count += 1;
}
// Subtract the count of items in list2
for (String item : list2) {
// If the map doesn't contain the item here, then this item wasn't in list1
if (!counts.containsKey(item)) return false;
counts.get(item).count -= 1;
}
// If any count is nonzero at this point, then the two lists don't match
for (Map.Entry<String, Count> entry : counts.entrySet()) {
if (entry.getValue().count != 0) return false;
}
return true;
}
I've been able to solve this by executing a dummy call ( e.g. IsAlive returning true ) just before the request with large content on the same wcf channel/client. Apparently ssl negotation is done on the first call. So no need to increase Uploadreadaheadsize.
(del
can be your friend, as it marks objects as being deletable when there no other references to them. Now, often the CPython interpreter keeps this memory for later use, so your operating system might not see the "freed" memory.)
Maybe you would not run into any memory problem in the first place by using a more compact structure for your data.
Thus, lists of numbers are much less memory-efficient than the format used by the standard array
module or the third-party numpy
module. You would save memory by putting your vertices in a NumPy 3xN array and your triangles in an N-element array.
If you want to handle IPV6 in standard notation there are 8 groups of 4 hex digits:
2001:0dc5:72a3:0000:0000:802e:3370:73E4
32 hex digits + 7 separators = 39 characters.
CAUTION: If you also want to hold IPV4 addresses mapped as IPV6 addresses, use 45 characters as @Deepak suggests.
You can get the HTML of the website with driver.getPageSource(). If the html does not change in a given interval of time this means that the page is done loading. One or two seconds should be enough. If you want to speed things up you can just compare the lenght of the two htmls. If their lenght is equal the htmls should be equal and that means the page is fully loaded. The JavaScript solution did not work for me.
If you want to escape characters with a \
, you have addcslashes()
. For example, if you want to escape only single quotes like the question, you can do:
echo addcslashes($value, "'");
And if you want to escape '
, "
, \
, and nul
(the byte null), you can use addslashes()
:
echo addslashes($value);
I like the parts method of Path for this:
grandparent_directory, parent_directory, filename = Path(export_filename).parts[-3:]
log.info(f'{t: <30}: {num_rows: >7} Rows exported to {grandparent_directory}/{parent_directory}/{filename}')
For <a>
tags:
You need to stick target="_self"
on your <a>
tag
There are three cases where AngularJS will perform a full page reload:
<a href="/ext/link?a=b" target="_self">link</a>
<a href="http://angularjs.org/">link</a>
<a href="/not-my-base/link">link</a>
Using javascript:
The $location
service allows you to change only the URL; it does not allow you to reload the page. When you need to change the URL and reload the page or navigate to a different page, please use a lower level API: $window.location.href
.
See:
I find the solution in spring.io,like this:
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
You should look for the error in the file error_log in the log directory. Maybe there are differences between your local and server configuration (db user/password etc.etc.)
usually the log file is in
/var/log/apache2/error.log
or
/var/log/httpd/error.log
// Earlier in your code
mysql_connect();
set_a_flag_that_db_is_connected();
// Later....
if (flag_is_set())
mysql_connect(....);
Here is a little fix for accepted solution, which prevents right column from falling under the left column. Replaced width: 100%;
with overflow: hidden;
a tricky solution, if somebody didn't know it.
<html>
<head>
<title>This is My Page's Title</title>
<style type="text/css">
#left {
float: left;
width: 180px;
background-color: #ff0000;
}
#right {
overflow: hidden;
background-color: #00FF00;
}
</style>
</head>
<body>
<div>
<div id="left">
left
</div>
<div id="right">
right
</div>
</div>
http://jsfiddle.net/MHeqG/2600/
[edit] Also check an example for three column layout: http://jsfiddle.net/MHeqG/3148/
PostgreSQL Forging Key DELETE, UPDATE CASCADE
CREATE TABLE apps_user(
user_id SERIAL PRIMARY KEY,
username character varying(30),
userpass character varying(50),
created_on DATE
);
CREATE TABLE apps_profile(
pro_id SERIAL PRIMARY KEY,
user_id INT4 REFERENCES apps_user(user_id) ON DELETE CASCADE ON UPDATE CASCADE,
firstname VARCHAR(30),
lastname VARCHAR(50),
email VARCHAR UNIQUE,
dob DATE
);
I was facing a similar issue. Actually the command is :
java -version and not java --version.
You will get output something like this:
java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)
You need an INSERT ... SELECT
INSERT INTO exception_codes( code, message )
SELECT code, message
FROM exception_code_tmp
I did this way:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="actionMenuTextAppearance">@style/MenuTextAppearance</item>
<item name="android:actionMenuTextAppearance">@style/MenuTextAppearance</item>
<item name="actionMenuTextColor">@color/colorAccent</item>
</style>
<style name="MenuTextAppearance" >
<item name="android:textAppearance">@android:style/TextAppearance.Large</item>
<item name="android:textSize">20sp</item>
<item name="android:textStyle">bold</item>
</style>
EDIT: After your comments, I understand that you want to pass variable through your form.
You can do this using hidden field:
<input type='hidden' name='var' value='<?php echo "$var";?>'/>
In PHP action File:
<?php
if(isset($_POST['var'])) $var=$_POST['var'];
?>
Or using sessions: In your first page:
$_SESSION['var']=$var;
start_session();
should be placed at the beginning of your php page.
In PHP action File:
if(isset($_SESSION['var'])) $var=$_SESSION['var'];
First Answer:
You can also use $GLOBALS
:
if (isset($_POST['save_exit']))
{
echo $GLOBALS['var'];
}
Check this documentation for more informations.