Add the following code into startup.cs
file.
public void ConfigureServices(IServiceCollection services)
{
string con = Configuration.GetConnectionString("DBConnection");
services.AddMvc();
GlobalProperties.DBConnection = con;//DBConnection is a user defined static property of GlobalProperties class
}
Use GlobalProperties.DBConnection
property in Context
class.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(GlobalProperties.DBConnection);
}
}
Take a look at this solution. As I know, Flashphoner allows to play Live audio+video stream in the pure HTML5 page.
They use MPEG1 and G.711 codecs for playback. The hack is rendering decoded video to HTML5 canvas element and playing decoded audio via HTML5 audio context.
To attempt command line arguments directly is not possible.
One alternative might be environment variables (https://superuser.com/questions/728951/systemd-giving-my-service-multiple-arguments).
This is where I found the answer: http://www.freedesktop.org/software/systemd/man/systemctl.html
so sudo systemctl restart myprog -v
-- systemctl will think you're trying to set one of its flags, not myprog's flag.
sudo systemctl restart myprog someotheroption
-- systemctl will restart myprog and the someotheroption service, if it exists.
If I understood the question correctly, you can use the slicing notation to keep everything except the last item:
record = record[:-1]
But a better way is to delete the item directly:
del record[-1]
Note 1: Note that using record = record[:-1] does not really remove the last element, but assign the sublist to record. This makes a difference if you run it inside a function and record is a parameter. With record = record[:-1] the original list (outside the function) is unchanged, with del record[-1] or record.pop() the list is changed. (as stated by @pltrdy in the comments)
Note 2: The code could use some Python idioms. I highly recommend reading this:
Code Like a Pythonista: Idiomatic Python (via wayback machine archive).
Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.
http://www.rgagnon.com/javadetails/java-0542.html
Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.
package filesendtest;
import java.io.*;
import java.net.*;
class TCPServer {
private final static String fileToSend = "C:\\test1.pdf";
public static void main(String args[]) {
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
if (outToClient != null) {
File myFile = new File( fileToSend );
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}
package filesendtest;
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;
class TCPClient {
private final static String serverIP = "127.0.0.1";
private final static int serverPort = 3248;
private final static String fileOutput = "C:\\testout.pdf";
public static void main(String args[]) {
byte[] aByte = new byte[1];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
try {
clientSocket = new Socket( serverIP , serverPort );
is = clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream( fileOutput );
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}
}
}
Related
Byte array of unknown length in java
Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):
public static String md5String(File file) {
try {
InputStream fin = new FileInputStream(file);
java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read;
do {
read = fin.read(buffer);
if (read > 0) {
md5er.update(buffer, 0, read);
}
} while (read != -1);
fin.close();
byte[] digest = md5er.digest();
if (digest == null) {
return null;
}
String strDigest = "0x";
for (int i = 0; i < digest.length; i++) {
strDigest += Integer.toString((digest[i] & 0xff)
+ 0x100, 16).substring(1).toUpperCase();
}
return strDigest;
} catch (Exception e) {
return null;
}
}
var pinIcon = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(12, 18)
);
Very good and remarkable question with a very interesting discussion! I also was using the Array.sort()
function after pushing a single element in an array with some thousands of objects.
I had to extend your locationOf
function for my purpose because of having complex objects and therefore the need for a compare function like in Array.sort()
:
function locationOf(element, array, comparer, start, end) {
if (array.length === 0)
return -1;
start = start || 0;
end = end || array.length;
var pivot = (start + end) >> 1; // should be faster than dividing by 2
var c = comparer(element, array[pivot]);
if (end - start <= 1) return c == -1 ? pivot - 1 : pivot;
switch (c) {
case -1: return locationOf(element, array, comparer, start, pivot);
case 0: return pivot;
case 1: return locationOf(element, array, comparer, pivot, end);
};
};
// sample for objects like {lastName: 'Miller', ...}
var patientCompare = function (a, b) {
if (a.lastName < b.lastName) return -1;
if (a.lastName > b.lastName) return 1;
return 0;
};
lblMeter.text=[NSString stringWithFormat:@"%.02f",[[dic objectForKey:@"distance"] floatValue]];
Use npm outdated
to see Current and Latest version of all packages.
Then npm i packageName@versionNumber
to install specific version : example npm i [email protected]
.
Or npm i packageName@latest
to install latest version : example npm i browser-sync@latest
.
Try this:
final View activityRootView = getWindow().getDecorView().getRootView();
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
//r will be populated with the coordinates of your view that area still visible.
activityRootView.getWindowVisibleDisplayFrame(r);
int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
if (heightDiff < activityRootView.getRootView().getHeight() / 4 ) { // if more than 100 pixels, its probably a keyboard...
// ... do something here ... \\
}
}
});
No. MySQL is not case sensitive, and neither is the SQL standard. It's just common practice to write the commands upper-case.
Now, if you are talking about table/column names, then yes they are, but not the commands themselves.
So
SELECT * FROM foo;
is the same as
select * from foo;
but not the same as
select * from FOO;
If Primary Key and type needed, this query may be useful:
SELECT L.TABLE_SCHEMA, L.TABLE_NAME, L.COLUMN_NAME, R.TypeName
FROM(
SELECT COLUMN_NAME, TABLE_NAME, TABLE_SCHEMA
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
)L
LEFT JOIN (
SELECT
OBJECT_NAME(c.OBJECT_ID) TableName ,c.name AS ColumnName ,t.name AS TypeName
FROM sys.columns AS c
JOIN sys.types AS t ON c.user_type_id=t.user_type_id
)R ON L.COLUMN_NAME = R.ColumnName AND L.TABLE_NAME = R.TableName
Or with Prototype:
Event.observe(this, 'load', function() { new Ajax.Request(... ) );
Or better, define the function elsewhere rather than inline, then:
Event.observe(this, 'load', functionName );
You don't have to use jQuery or Prototype specifically, but I hope you're using some kind of library. Either library is going to handle the event handling in a more consistent manner than onload, and of course is going to make it much easier to process the Ajax call. If you must use the body onload attribute, then you should just be able to call the same function as referenced in these examples (onload="javascript:functionName();"
).
However, if your database update doesn't depend on the rendering on the page, why wait until it's fully loaded? You could just include a call to the Ajax-calling function at the end of the JavaScript on the page, which should give nearly the same effect.
Where is the file that you're running? If it is in your public html folder, you can do echo dirname(__FILE__);
The simplest is to use replace:
"foo bar\t".replace(" ", "").replace("\t", "")
Alternatively, use a regular expression:
import re
re.sub(r"\s", "", "foo bar\t")
On Excel 2010 try this:
AndroidManifest.xml:
<uses-sdk
android:minSdkVersion=...
android:targetSdkVersion="11" />
and
Project Properties -> Project Build Target = 11 or above
These 2 things fixed the problem for me!
The error message says it all: your connection timed out. This means your request did not get a response within some (default) timeframe. The reasons that no response was received is likely to be one of:
Note that firewalls and port or IP blocking may be in place by your ISP
It makes sure that the returned object (which is an RValue at that point) can't be modified. This makes sure the user can't do thinks like this:
myFunc() = Object(...);
That would work nicely if myFunc
returned by reference, but is almost certainly a bug when returned by value (and probably won't be caught by the compiler). Of course in C++11 with its rvalues this convention doesn't make as much sense as it did earlier, since a const object can't be moved from, so this can have pretty heavy effects on performance.
For SQL Server 2012, or later, an easier solution is to use FORMAT ()
Documentation.
EG:
SELECT Format(1234567.8, '##,##0')
Results in: 1,234,568
Change the minDate dynamically
.datepicker("destroy")
For example
<script>
$(function() {
$( "#datepicker" ).datepicker("destroy");
$( "#datepicker" ).datepicker();
});
</script>
<p>Date: <input type="text" id="datepicker" /></p>
innerText is the current correct answer for this. The other answers are outdated and incorrect.
document.getElementById('ShowButton').innerText = 'Show filter';
innerHTML also works, and can be used to insert HTML.
You are to use something like this:
start /d C:\Windows\System32\calc.exe
start /d "C:\Program Files\Mozilla
Firefox" firefox.exe start /d
"C:\Program Files\Microsoft
Office\Office12" EXCEL.EXE
Also I advice you to use special batch files editor - Dr.Batcher
ezpz's answer is almost perfect, but I hope I can add a little more.
Geo asked about time in milliseconds; this sounds like an integer quantity, and I wouldn't take the detour through floating-point land. Thus my approach would be:
irb(main):038:0> t8 = Time.now
=> Sun Nov 01 15:18:04 +0100 2009
irb(main):039:0> t9 = Time.now
=> Sun Nov 01 15:18:18 +0100 2009
irb(main):040:0> dif = t9 - t8
=> 13.940166
irb(main):041:0> (1000 * dif).to_i
=> 13940
Multiplying by an integer 1000 preserves the fractional number perfectly and may be a little faster too.
If you're dealing with dates and times, you may need to use the DateTime class. This works similarly but the conversion factor is 24 * 3600 * 1000 = 86400000 .
I've found DateTime's strptime and strftime functions invaluable in parsing and formatting date/time strings (e.g. to/from logs). What comes in handy to know is:
The formatting characters for these functions (%H, %M, %S, ...) are almost the same as for the C functions found on any Unix/Linux system; and
There are a few more: In particular, %L does milliseconds!
In SQL Server type:
Select 'Your Text'
There is no need for the FROM
or WHERE
clause.
You can retrieve the format strings from the CultureInfo
DateTimeFormat
property, which is a DateTimeFormatInfo
instance. This in turn has properties like ShortDatePattern
and ShortTimePattern
, containing the format strings:
CultureInfo us = new CultureInfo("en-US");
string shortUsDateFormatString = us.DateTimeFormat.ShortDatePattern;
string shortUsTimeFormatString = us.DateTimeFormat.ShortTimePattern;
CultureInfo uk = new CultureInfo("en-GB");
string shortUkDateFormatString = uk.DateTimeFormat.ShortDatePattern;
string shortUkTimeFormatString = uk.DateTimeFormat.ShortTimePattern;
If you simply want to format the date/time using the CultureInfo
, pass it in as your IFormatter
when converting the DateTime
to a string, using the ToString
method:
string us = myDate.ToString(new CultureInfo("en-US"));
string uk = myDate.ToString(new CultureInfo("en-GB"));
For those who like to reduce typing (i.e., everyone!): pd.set_option('max_colwidth', None)
does the same thing
Be aware that this property isn't as useful as many people think it is. Just because your app is running on a Windows machine, for example, doesn't mean the file it's reading will be using Windows-style line separators. Many web pages contain a mixture of "\n" and "\r\n", having been cobbled together from disparate sources. When you're reading text as a series of logical lines, you should always look for all three of the major line-separator styles: Windows ("\r\n"), Unix/Linux/OSX ("\n") and pre-OSX Mac ("\r").
When you're writing text, you should be more concerned with how the file will be used than what platform you're running on. For example, if you expect people to read the file in Windows Notepad, you should use "\r\n" because it only recognizes the one kind of separator.
I'm pretty sure it is technically impossible in SQL Server to have a True 1 to 1 relationship, as that would mean you would have to insert both records at the same time (otherwise you'd get a constraint error on insert), in both tables, with both tables having a foreign key relationship to each other.
That being said, your database design described with a foreign key is a 1 to 0..1 relationship. There is no constrain possible that would require a record in tableB. You can have a pseudo-relationship with a trigger that creates the record in tableB.
So there are a few pseudo-solutions
First, store all the data in a single table. Then you'll have no issues in EF.
Or Secondly, your entity must be smart enough to not allow an insert unless it has an associated record.
Or thirdly, and most likely, you have a problem you are trying to solve, and you are asking us why your solution doesn't work instead of the actual problem you are trying to solve (an XY Problem).
UPDATE
To explain in REALITY how 1 to 1 relationships don't work, I'll use the analogy of the Chicken or the egg dilemma. I don't intend to solve this dilemma, but if you were to have a constraint that says in order to add a an Egg to the Egg table, the relationship of the Chicken must exist, and the chicken must exist in the table, then you couldn't add an Egg to the Egg table. The opposite is also true. You cannot add a Chicken to the Chicken table without both the relationship to the Egg and the Egg existing in the Egg table. Thus no records can be every made, in a database without breaking one of the rules/constraints.
Database nomenclature of a one-to-one relationship is misleading. All relationships I've seen (there-fore my experience) would be more descriptive as one-to-(zero or one) relationships.
(at least) for Django 1.8:
If you use
if settings.DEBUG:
urlpatterns.append(url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))
as described above, make sure that no "catch all" url pattern, directing to a default view, comes before that in urlpatterns = []. As .append will put the added scheme to the end of the list, it will of course only be tested if no previous url pattern matches. You can avoid that by using something like this where the "catch all" url pattern is added at the very end, independent from the if statement:
if settings.DEBUG:
urlpatterns.append(url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))
urlpatterns.append(url(r'$', 'views.home', name='home')),
In my opinion, the important thing about the default export is that it can be imported with any name!
If there is a file, foo.js, which exports default:
export default function foo(){}
_x000D_
it can be imported in bar.js using:
import bar from 'foo'
import Bar from 'foo' // Or ANY other name you wish to assign to this import
_x000D_
The best practice for this situation. Use RETURNING … INTO
.
INSERT INTO teams VALUES (...) RETURNING id INTO last_id;
Note this is for PLPGSQL
Regardless of the version, for your example, the <update>
is:
{ $set: { lastLookedAt: Date.now() / 1000 } }
However, depending on your version of MongoDB, the query will look different. Regardless of version, the key is that the empty condition {}
will match any document. In the Mongo shell, or with any MongoDB client:
db.foo.updateMany( {}, <update> )
{}
is the condition (the empty condition matches any document)db.foo.update( {}, <update>, { multi: true } )
{}
is the condition (the empty condition matches any document){multi: true}
is the "update multiple documents" optiondb.foo.update( {}, <update>, false, true )
{}
is the condition (the empty condition matches any document)false
is for the "upsert" parametertrue
is for the "multi" parameter (update multiple records)Put a div
inside td
and give following style width:50px;overflow: hidden;
to the div
Jsfiddle link
<td>
<div style="width:50px;overflow: hidden;">
<span>A long string more than 50px wide</span>
</div>
</td>
I usually add separate safe pipe reusable component as following
# Add Safe Pipe
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({name: 'mySafe'})
export class SafePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {
}
public transform(url) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}
# then create shared pipe module as following
import { NgModule } from '@angular/core';
import { SafePipe } from './safe.pipe';
@NgModule({
declarations: [
SafePipe
],
exports: [
SafePipe
]
})
export class SharedPipesModule {
}
# import shared pipe module in your native module
@NgModule({
declarations: [],
imports: [
SharedPipesModule,
],
})
export class SupportModule {
}
<!-------------------
call your url (`trustedUrl` for me) and add `mySafe` as defined in Safe Pipe
---------------->
<div class="container-fluid" *ngIf="trustedUrl">
<iframe [src]="trustedUrl | mySafe" align="middle" width="100%" height="800" frameborder="0"></iframe>
</div>
The benefit of a generator expression is that it uses less memory since it doesn't build the whole list at once. Generator expressions are best used when the list is an intermediary, such as summing the results, or creating a dict out of the results.
For example:
sum(x*2 for x in xrange(256))
dict( (k, some_func(k)) for k in some_list_of_keys )
The advantage there is that the list isn't completely generated, and thus little memory is used (and should also be faster)
You should, though, use list comprehensions when the desired final product is a list. You are not going to save any memeory using generator expressions, since you want the generated list. You also get the benefit of being able to use any of the list functions like sorted or reversed.
For example:
reversed( [x*2 for x in xrange(256)] )
You can always apply CCS class with rotate
property - http://css-tricks.com/snippets/css/text-rotation/
To keep rotated image within your div
dimensions you need to adjust CSS as well, there is no needs to use JavaScript except of adding class.
Here is an Enum
factory that avoids realm issues by using a namespace and Symbol.for
:
const Enum = (n, ...v) => Object.freeze(v.reduce((o, v) => (o[v] = Symbol.for(`${n}.${v}`), o), {}));
const COLOR = Enum("ACME.Color", "Blue", "Red");
console.log(COLOR.Red.toString());
console.log(COLOR.Red === Symbol.for("ACME.Color.Red"));
_x000D_
This is because you are referring to property of controller named HttpContext
. To access the current context use full class name:
System.Web.HttpContext.Current
However this is highly not recommended to access context like this in ASP.NET MVC, so yes, you can think of System.Web.HttpContext.Current
as being deprecated inside ASP.NET MVC. The correct way to access current context is
this.ControllerContext.HttpContext
or if you are inside a Controller, just use member
this.HttpContext
I wonder that everyone has posted about value
and text
option to get from <option>
and no one suggested label
.
So I am suggesting label
too, as supported by all browsers
To get value
(same as others suggested)
function test(a) {
var x = a.options[a.selectedIndex].value;
alert(x);
}
To get option
text
(i.e. Communication or -Select-)
function test(a) {
var x = a.options[a.selectedIndex].text;
alert(x);
}
OR (New suggestion)
function test(a) {
var x = a.options[a.selectedIndex].label;
alert(x);
}
HTML
<select onchange="test(this)" id="select_id">
<option value="0">-Select-</option>
<option value="1">Communication</option>
<option value="2" label=‘newText’>Communication</option>
</select>
Note: In above HTML for
option
value 2,label
will return newText instead of Communication
Also
Note: It is not possible to set the label property in Firefox (only return).
>>> import re
>>> st = " i think mabe 124 + <font color=\"black\"><font face=\"Times New Roman\">but I don't have a big experience it just how I see it in my eyes <font color=\"green\"><font face=\"Arial\">fun stuff"
>>> re.sub("<.*?>","",st)
" i think mabe 124 + but I don't have a big experience it just how I see it in my eyes fun stuff"
>>>
If you want to dump the entire db as csv
#!/bin/bash
host=hostname
uname=username
pass=password
port=portnr
db=db_name
s3_url=s3://bxb2-anl-analyzed-pue2/bxb_ump/db_dump/
DATE=`date +%Y%m%d`
rm -rf $DATE
echo 'show tables' | mysql -B -h${host} -u${uname} -p${pass} -P${port} ${db} > tables.txt
awk 'NR>1' tables.txt > tables_new.txt
while IFS= read -r line
do
mkdir -p $DATE/$line
echo "select * from $line" | mysql -B -h"${host}" -u"${uname}" -p"${pass}" -P"${port}" "${db}" > $DATE/$line/dump.tsv
done < tables_new.txt
touch $DATE/$DATE.fin
rm -rf tables_new.txt tables.txt
html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"
</head>
<body>
<ul class="menu">
<li><a href="#">My Dashboard</a>
<ul>
<li><a href="#" class="learn">Learn</a></li>
<li><a href="#" class="teach">Teach</a></li>
<li><a href="#" class="Mylibrary">My Library</a></li>
</ul>
</li>
<li><a href="#">Likes</a>
<ul>
<li><a href="#" class="Pics">Pictures</a></li>
<li><a href="#" class="audio">Audio</a></li>
<li><a href="#" class="Videos">Videos</a></li>
</ul>
</li>
<li><a href="#">Views</a>
<ul>
<li><a href="#" class="documents">Documents</a></li>
<li><a href="#" class="messages">Messages</a></li>
<li><a href="#" class="signout">Videos</a></li>
</ul>
</li>
<li><a href="#">account</a>
<ul>
<li><a href="#" class="SI">Sign In</a></li>
<li><a href="#" class="Reg">Register</a></li>
<li><a href="#" class="Deactivate">Deactivate</a></li>
</ul>
</li>
<li><a href="#">Uploads</a>
<ul>
<li><a href="#" class="Pics">Pictures</a></li>
<li><a href="#" class="audio">Audio</a></li>
<li><a href="#" class="Videos">Videos</a></li>
</ul>
</li>
<li><a href="#">Videos</a>
<ul>
<li><a href="#" class="Add">Add</a></li>
<li><a href="#" class="delete">Delete</a></li>
</ul>
</li>
<li><a href="#">Documents</a>
<ul>
<li><a href="#" class="Add">Upload</a></li>
<li><a href="#" class="delete">Download</a></li>
</ul>
</li>
</ul>
</body>
</html>
css:
.menu,
.menu ul,
.menu li,
.menu a {
margin: 0;
padding: 0;
border: none;
outline: none;
}
body{
max-width:110%;
margin-left:0;
}
.menu {
height: 40px;
width:110%;
margin-left:-4px;
margin-top:-10px;
background: #4c4e5a;
background: -webkit-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
background: -moz-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
background: -o-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
background: -ms-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
background: linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
.menu li {
position: relative;
list-style: none;
float: left;
display: block;
height: 40px;
}
.menu li a {
display: block;
padding: 0 14px;
margin: 6px 0;
line-height: 28px;
text-decoration: none;
border-left: 1px solid #393942;
border-right: 1px solid #4f5058;
font-family: Helvetica, Arial, sans-serif;
font-weight: bold;
font-size: 13px;
color: #f3f3f3;
text-shadow: 1px 1px 1px rgba(0,0,0,.6);
-webkit-transition: color .2s ease-in-out;
-moz-transition: color .2s ease-in-out;
-o-transition: color .2s ease-in-out;
-ms-transition: color .2s ease-in-out;
transition: color .2s ease-in-out;
}
.menu li:first-child a { border-left: none; }
.menu li:last-child a{ border-right: none; }
.menu li:hover > a { color: #8fde62; }
.menu ul {
position: absolute;
top: 40px;
left: 0;
opacity: 0;
background: #1f2024;
-webkit-border-radius: 0 0 5px 5px;
-moz-border-radius: 0 0 5px 5px;
border-radius: 0 0 5px 5px;
-webkit-transition: opacity .25s ease .1s;
-moz-transition: opacity .25s ease .1s;
-o-transition: opacity .25s ease .1s;
-ms-transition: opacity .25s ease .1s;
transition: opacity .25s ease .1s;
}
.menu li:hover > ul { opacity: 1; }
.menu ul li {
height: 0;
overflow: hidden;
padding: 0;
-webkit-transition: height .25s ease .1s;
-moz-transition: height .25s ease .1s;
-o-transition: height .25s ease .1s;
-ms-transition: height .25s ease .1s;
transition: height .25s ease .1s;
}
.menu li:hover > ul li {
height: 36px;
overflow: visible;
padding: 0;
}
.menu ul li a {
width: 100px;
padding: 4px 0 4px 40px;
margin: 0;
border: none;
border-bottom: 1px solid #353539;
}
.menu ul li:last-child a { border: none; }
demo here
try also resizing the browser tab to see it in action
Server-side, write:
if(IsPostBack)
{
// NOTE: the following uses an overload of RegisterClientScriptBlock()
// that will surround our string with the needed script tags
ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var isPostBack = true;", true);
}
Then, in your script which runs for the onLoad, check for the existence of that variable:
if(isPostBack) {
// do your thing
}
You don't really need to set the variable otherwise, like Jonathan's solution. The client-side if statement will work fine because the "isPostBack" variable will be undefined, which evaluates as false in that if statement.
In my case the file is a shell script (*.sh
file) meant to deploy our project to a local development server, for my developers.
The shell script should work consistently and may be updated; so I tracked it in the same Git project as the code which the script is meant to deploy.
The shell script runs one executable, and then allows that executable to run; so the script is still running; so my shell still has the script open; so it's locked.
I Ctrl+C
'd to kill the script (so now my local dev server is no longer accessible), now I can checkout freely.
Your hack of decrementing the count at the end is exactly that -- a hack.
Far better to write your loop correctly in the first place, so it doesn't count the last line twice.
int main() {
int number_of_lines = 0;
std::string line;
std::ifstream myfile("textexample.txt");
while (std::getline(myfile, line))
++number_of_lines;
std::cout << "Number of lines in text file: " << number_of_lines;
return 0;
}
Personally, I think in this case, C-style code is perfectly acceptable:
int main() {
unsigned int number_of_lines = 0;
FILE *infile = fopen("textexample.txt", "r");
int ch;
while (EOF != (ch=getc(infile)))
if ('\n' == ch)
++number_of_lines;
printf("%u\n", number_of_lines);
return 0;
}
Edit: Of course, C++ will also let you do something a bit similar:
int main() {
std::ifstream myfile("textexample.txt");
// new lines will be skipped unless we stop it from happening:
myfile.unsetf(std::ios_base::skipws);
// count the newlines with an algorithm specialized for counting:
unsigned line_count = std::count(
std::istream_iterator<char>(myfile),
std::istream_iterator<char>(),
'\n');
std::cout << "Lines: " << line_count << "\n";
return 0;
}
select max(m.mark) as maxMarkObtained,su.Subname from Student s
inner join Marks m on s.Stid=m.Stid inner join [Subject] su on
su.Subid=m.Subid group by su.Subname
I have execute it , this should work.
I encountered the same problem in child components where initially it would have to have the current value of the Subject, then subscribe to the Subject to listen to changes. I just maintain the current value in the Service so it is available for components to access, e.g. :
import {Storage} from './storage';
import {Injectable} from 'angular2/core';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class SessionStorage extends Storage {
isLoggedIn: boolean;
private _isLoggedInSource = new Subject<boolean>();
isLoggedIn = this._isLoggedInSource.asObservable();
constructor() {
super('session');
this.currIsLoggedIn = false;
}
setIsLoggedIn(value: boolean) {
this.setItem('_isLoggedIn', value, () => {
this._isLoggedInSource.next(value);
});
this.isLoggedIn = value;
}
}
A component that needs the current value could just then access it from the service, i.e,:
sessionStorage.isLoggedIn
Not sure if this is the right practice :)
Since you already seem to have solved the basic pointer address display, here's how you would check the address of a double pointer:
char **a;
char *b;
char c = 'H';
b = &c;
a = &b;
You would be able to access the address of the double pointer a
by doing:
printf("a points at this memory location: %p", a);
printf("which points at this other memory location: %p", *a);
If you need to pass the asterisk symbol, you have to wrap it with quotes.
In my case, I need to configure cors for websockets. So, I decided to put cors urls into application.yml. For prod env I'll use specific urls, but for dev it's ok to use just *.
In yml file I have:
websocket:
cors: "*"
In Config class I have:
@Value("${websocket.cors}")
private String[] cors;
Use this for GET values:
Request.QueryString["key"]
And this for POST values
Request.Form["key"]
Also, this will work if you don't care whether it comes from GET or POST, or the HttpContext.Items collection:
Request["key"]
Another thing to note (if you need it) is you can check the type of request by using:
Request.RequestType
Which will be the verb used to access the page (usually GET or POST). Request.IsPostBack
will usually work to check this, but only if the POST request includes the hidden fields added to the page by the ASP.NET framework.
It turns out the answer was ridiculously simple, but mystifying as to why it was necessary.
In the IIS Manager on the server, I set the application pool for my web application to not allow 32-bit assemblies.
It seems it assumes, on a 64-bit system, that you must want the 32 bit assembly. Bizarre.
You will certainly have to use both STR_TO_DATE
to convert your date to a MySQL standard date format, and UNIX_TIMESTAMP
to get the timestamp from it.
Given the format of your date, something like
UNIX_TIMESTAMP(STR_TO_DATE(Sales.SalesDate, '%M %e %Y %h:%i%p'))
Will gives you a valid timestamp. Look the STR_TO_DATE
documentation to have more information on the format string.
Thanks Aakash for recommending JIDE MultilineLabel. JIDE's StyledLabel is also enhanced recently to support multiple line. I would recommend it over the MultilineLabel as it has many other great features. You can check out an article on StyledLabel below. It is still free and open source.
Not really an answer to the specific question, but if there are others, like me, who are getting this error in fastAPI and end up here:
It is probably because your route response has a value that can't be JSON serialised by jsonable_encoder
. For me it was WKBElement: https://github.com/tiangolo/fastapi/issues/2366
Like in the issue, I ended up just removing the value from the output.
You are correct in that it's not "right" to add files to the tags folder.
You've correctly guessed that copy
is the operation to use; it lets Subversion keep track of the history of these files, and also (I assume) store them much more efficiently.
In my experience, it's best to do copies ("snapshots") of entire projects, i.e. all files from the root check-out location. That way the snapshot can stand on its own, as a true representation of the entire project's state at a particular point in time.
This part of "the book" shows how the command is typically used.
Also possible to use:
pkill -f "Process name"
For me, it worked up perfectly. It was what I have been looking for. pkill doesn't work with name without the flag.
When -f
is set, the full command line is used for pattern matching.
You are passing a dictionary to a function that expects a string.
This syntax:
{"('Hello',)": 6, "('Hi',)": 5}
is both a valid Python dictionary literal and a valid JSON object literal. But loads
doesn't take a dictionary; it takes a string, which it then interprets as JSON and returns the result as a dictionary (or string or array or number, depending on the JSON, but usually a dictionary).
If you pass this string to loads
:
'''{"('Hello',)": 6, "('Hi',)": 5}'''
then it will return a dictionary that looks a lot like the one you are trying to pass to it.
You could also exploit the similarity of JSON object literals to Python dictionary literals by doing this:
json.loads(str({"('Hello',)": 6, "('Hi',)": 5}))
But in either case you would just get back the dictionary that you're passing in, so I'm not sure what it would accomplish. What's your goal?
this will set your session to keep everything till the browser is closed
session.setMaxinactiveinterval(-1);
and this should set it for 1 day
session.setMaxInactiveInterval(60*60*24);
You can use the following nginx configuration example:
upstream adminhost {
server adminhostname:8080;
}
server {
listen 80;
location ~ ^/admin/(.*)$ {
proxy_pass http://adminhost/$1$is_args$args;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
}
}
If you know you're going to have a limited number of max options then I would try this (example for max of 4 options per order):
Select OI.ID, OI.Item_Name, OO1.Value, OO2.Value, OO3.Value, OO4.Value FROM Ordered_Items OI LEFT JOIN Ordered_Options OO1 ON OO1.Ordered_Item_ID = OI.ID LEFT JOIN Ordered_Options OO2 ON OO2.Ordered_Item_ID = OI.ID AND OO2.ID != OO1.ID LEFT JOIN Ordered_Options OO3 ON OO3.Ordered_Item_ID = OI.ID AND OO3.ID != OO1.ID AND OO3.ID != OO2.ID LEFT JOIN Ordered_Options OO4 ON OO4.Ordered_Item_ID = OI.ID AND OO4.ID != OO1.ID AND OO4.ID != OO2.ID AND OO4.ID != OO3.ID GROUP BY OI.ID, OI.Item_Name
The group by condition gets rid of all of the duplicates that you would otherwise get. I've just implemented something similar on a site I'm working on where I knew I'd always have 1 or 2 matched in my child table, and I wanted to make sure I only had 1 row for each parent item.
I was looking for a way to do this myself and figured out a simple solution.
I'm assuming that you started a default Win32 Project (Windows application) in Visual Studio, which provides a "WinMain" function. By default, Visual Studio sets the entry point to "SUBSYSTEM:WINDOWS". You need to first change this by going to:
Project -> Properties -> Linker -> System -> Subsystem
And select "Console (/SUBSYSTEM:CONSOLE)" from the drop-down list.
Now, the program will not run, since a "main" function is needed instead of the "WinMain" function.
So now you can add a "main" function like you normally would in C++. After this, to start the GUI program, you can call the "WinMain" function from inside the "main" function.
The starting part of your program should now look something like this:
#include <iostream>
using namespace std;
// Main function for the console
int main(){
// Calling the wWinMain function to start the GUI program
// Parameters:
// GetModuleHandle(NULL) - To get a handle to the current instance
// NULL - Previous instance is not needed
// NULL - Command line parameters are not needed
// 1 - To show the window normally
wWinMain(GetModuleHandle(NULL), NULL,NULL, 1);
system("pause");
return 0;
}
// Function for entry into GUI program
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
// This will display "Hello World" in the console as soon as the GUI begins.
cout << "Hello World" << endl;
.
.
.
Now you can use functions to output to the console in any part of your GUI program for debugging or other purposes.
What about wrapping it in a container. Container shoud have style like:
{
width:100%;
border: 10px solid transparent;
}
Download the appropriate APR based tomcat native library for your operating system so that Apache tomcat server can take some advantage of the feature of your OS which is not included by default in tomcat. For windows it will be a .dll
file.
I too got the warning while starting the server and you don't have to worry about this if you are testing or developing. This is meant to be on production purposes. After putting the tcnative-1.dll file inside the bin folder of Apache Tomcat 7 following are the output in the stderr file,
Apr 07, 2015 1:14:12 PM org.apache.catalina.core.AprLifecycleListener init
INFO: Loaded APR based Apache Tomcat Native library 1.1.33 using APR version 1.5.1.
Apr 07, 2015 1:14:12 PM org.apache.catalina.core.AprLifecycleListener init
INFO: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
Apr 07, 2015 1:14:14 PM org.apache.catalina.core.AprLifecycleListener initializeSSL
INFO: OpenSSL successfully initialized (OpenSSL 1.0.1m 19 Mar 2015)
Apr 07, 2015 1:14:14 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-apr-127.0.0.1"]
SELECT create_date
FROM sys.tables
WHERE name='YourTableName'
.sectionA[id='content'] { color : red; }
Won't work when the doctype is html 4.01 though...
Grokking lookaround rapidly.
How to distinguish lookahead and lookbehind?
Take 2 minutes tour with me:
(?=) - positive lookahead
(?<=) - positive lookbehind
Suppose
A B C #in a line
Now, we ask B, Where are you?
B has two solutions to declare it location:
One, B has A ahead and has C bebind
Two, B is ahead(lookahead) of C and behind (lookhehind) A.
As we can see, the behind and ahead are opposite in the two solutions.
Regex is solution Two.
Update: since the answer from @r2evans, it is much easier to insert images into R Markdown and control the size of the image.
The bookdown book does a great job of explaining that the best way to include images is by using include_graphics()
. For example, a full width image can be printed with a caption below:
```{r pressure, echo=FALSE, fig.cap="A caption", out.width = '100%'}
knitr::include_graphics("temp.png")
```
The reason this method is better than the pandoc approach ![your image](path/to/image)
:
fig.width
), the output width in the report (out.width
), add captions (fig.cap
) etc.knitr::kable()
is the best way to include tables in an R Markdown report as explained fully here. Again, this function is intelligent in automatically selecting the correct formatting for the output selected.
```{r table}
knitr::kable(mtcars[1:5,, 1:5], caption = "A table caption")
```
If you want to make your own simple tables in R Markdown and are using R Studio, you can check out the insert_table
package. It provides a tidy graphical interface for making tables.
Achieving custom styling of the table column width is beyond the scope of knitr
, but the kableExtra
package has been written to help achieve this: https://cran.r-project.org/web/packages/kableExtra/index.html
The R Markdown cheat sheet is still the best place to learn about most the basic syntax you can use.
If you are looking for potential extensions to the formatting, the bookdown
package is also worth exploring. It provides the ability to cross-reference, create special headers and more: https://bookdown.org/yihui/bookdown/markdown-extensions-by-bookdown.html
To use BeginForm
, here's the way to use it:
using(Html.BeginForm("uploadfiles",
"home", FormMethod.POST, new Dictionary<string, object>(){{"type", "file"}})
How about print (x, y)
at once.
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54
plt.plot(A,B)
for xy in zip(A, B): # <--
ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--
plt.grid()
plt.show()
Here's the config for ISAPI_Rewrite 3:
RewriteBase /
RewriteCond %{HTTP_HOST} ^mysite.org.uk$ [NC]
RewriteRule ^stuff/(.+)$ http://stuff.mysite.org.uk/$1 [NC,R=301,L]
I'm one of the noob too when I encountered something like this. So... I set the passwords using the command security page gave me: /opt/lampp/lampp security Then I used password xyz for all the passwords... Then when I go to site/, it ask for a basic authentication. But when I tried root//xyz, it does not allow me login. So, after some digging, it turns out the xyz password was set for a default user named 'lampp'. When I tried to login using lampp//xyz, it worked like a charm.
The issue is that they made an assumption that everyone knows to use lampp//rootpw as their login o.O And... that is a basic auth for the directory! not pw for phpmyadmin or pw for mysql...
don't make it so difficult you can simply find in phpinfo();
Hope helpful!
Thanks
Once you have the file-loader configured in the webpack.config, whenever you use import/require it tests the path against all loaders, and in case there is a match it passes the contents through that loader. In your case, it matched
{
test: /\.(jpe?g|png|gif|svg)$/i,
loader: "file-loader?name=/public/icons/[name].[ext]"
}
// For newer versions of Webpack it should be
{
test: /\.(jpe?g|png|gif|svg)$/i,
loader: 'file-loader',
options: {
name: '/public/icons/[name].[ext]'
}
}
and therefore you see the image emitted to
dist/public/icons/imageview_item_normal.png
which is the wanted behavior.
The reason you are also getting the hash file name, is because you are adding an additional inline file-loader. You are importing the image as:
'file!../../public/icons/imageview_item_normal.png'.
Prefixing with file!
, passes the file into the file-loader again, and this time it doesn't have the name configuration.
So your import should really just be:
import img from '../../public/icons/imageview_item_normal.png'
Update
As noted by @cgatian, if you actually want to use an inline file-loader, ignoring the webpack global configuration, you can prefix the import with two exclamation marks (!!):
import '!!file!../../public/icons/imageview_item_normal.png'.
After importing the png, the img
variable only holds the path the file-loader "knows about", which is public/icons/[name].[ext]
(aka "file-loader? name=/public/icons/[name].[ext]"
). Your output dir "dist" is unknown.
You could solve this in two ways:
publicPath
property to your output config, that points to your output directory (in your case ./dist).Example:
output: {
path: PATHS.build,
filename: 'app.bundle.js',
publicPath: PATHS.build
},
Lets get a visual impression about what was already said. For example you have a table with some tasks:
SELECT a.id,a.status,a.description FROM minicloud_tasks as a ORDER BY random();
id | status | description
----+------------+------------------
4 | processing | work on postgres
6 | deleted | need some rest
3 | pending | garden party
5 | completed | work on html
And you want to order the list of tasks by its status. The status is a list of string values:
(processing, pending, completed, deleted)
The trick is to give each status value an interger and order the list numerical:
SELECT a.id,a.status,a.description FROM minicloud_tasks AS a
JOIN (
VALUES ('processing', 1), ('pending', 2), ('completed', 3), ('deleted', 4)
) AS b (status, id) ON (a.status = b.status)
ORDER BY b.id ASC;
Which leads to:
id | status | description
----+------------+------------------
4 | processing | work on postgres
3 | pending | garden party
5 | completed | work on html
6 | deleted | need some rest
Credit @user80168
If you are interested in it being realtime, then what you need is to add in a pre-processing filter to determine what gets scanned with the heavy-duty stuff. A good fast, very real time, pre-processing filter that will allow you to scan things that are more likely to be a coca-cola can than not before moving onto more iffy things is something like this: search the image for the biggest patches of color that are a certain tolerance away from the sqrt(pow(red,2) + pow(blue,2) + pow(green,2))
of your coca-cola can. Start with a very strict color tolerance, and work your way down to more lenient color tolerances. Then, when your robot runs out of an allotted time to process the current frame, it uses the currently found bottles for your purposes. Please note that you will have to tweak the RGB colors in the sqrt(pow(red,2) + pow(blue,2) + pow(green,2))
to get them just right.
Also, this is gona seem really dumb, but did you make sure to turn on -oFast
compiler optimizations when you compiled your C code?
What's wrong with
import sys
from os.path import dirname, abspath
local_dir = abspath(dirname(__file__))
sys.path.append(local_dir)
import somescript
or better still wrap the functionality in a function, e.g. baz, then do this.
import sys
from os.path import dirname, abspath
local_dir = abspath(dirname(__file__))
sys.path.append(local_dir)
import somescript
somescript.baz()
There seem to be a lot of scripts starting python processes or forking, is that a requirement?
No, you can't get it quite like background-size:cover
but..
This approach is pretty damn close: it uses JavaScript to determine if the image is landscape or portrait, and applies styles accordingly.
JS
$('.myImages img').load(function(){
var height = $(this).height();
var width = $(this).width();
console.log('widthandheight:',width,height);
if(width>height){
$(this).addClass('wide-img');
}else{
$(this).addClass('tall-img');
}
});
CSS
.tall-img{
margin-top:-50%;
width:100%;
}
.wide-img{
margin-left:-50%;
height:100%;
}
Remove duplicate values from an associative array in PHP.
$arrDup = Array ('0' => 'aaa-aaa' , 'SKU' => 'aaa-aaa' , '1' => '12/1/1' , 'date' => '12/1/1' , '2' => '1.15' , 'cost' => '1.15' );
foreach($arrDup as $k => $v){
if(!( isset ($hold[$v])))
$hold[$v]=1;
else
unset($arrDup[$k]);
}
Array ( [0] => aaa-aaa [1] => 12/1/1 [2] => 1.15 )
For Unix Users
find ~/.m2 -name "*.lastUpdated" -exec grep -q "Could not transfer" {} \; -print -exec rm {} \;
Right-click your project and choose Update Dependencies
For Windows
for /r %i in (*.lastUpdated) do del %i
It totally depends upon which implementation you have used, whether arraylist linkedlist, or other implementations of set.
if it is set then you can directly get the first element , their can be trick loop over the collection , create a variable of value 1 and get value when flag value is 1 after that break that loop.
if it is list's implementation then it is easy by defining index number.
Years ago MSIE 5 or 5.5 (and probably both) had some serious issue with a "-" in the HTML block if you can believe it. Alhough it's not directly related, ever since we've stored an MD5 hash (containing letters and numbers only) in the cookie to look up everything else in server-side database.
You may be able to use the built-in function dir()
to produce similar behavior to PHP's isset()
, something like:
if 'foo' in dir(): # returns False, foo is not defined yet.
pass
foo = 'b'
if 'foo' in dir(): # returns True, foo is now defined and in scope.
pass
dir()
returns a list of the names in the current scope, more information can be found here: http://docs.python.org/library/functions.html#dir.
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
EDIT From Your comments i have edited the onclick view in this the button1 and button2 functions will be executed separately.
public onClick(View v){
switch(v.getId()){
case R.id.button1:
//Your button 1 function
break;
case R.id. button2:
//Your button 2 function
break;
}
}
I didn't want to mess with additional libraries. Simple ways suggested here didn't work out either. Finally, not on the request object, but I could get a GET parameter w/o all that hassle via self.GET.get('XXX')
:
...
def get_context_data(self, **kwargs):
context = super(SomeView, self).get_context_data(**kwargs)
context['XXX'] = self.GET.get('XXX')
...
Python 2.7.18, Django 1.11.20
I realize this question is old, however I ran into this same situation today and wanted to throw in my 2 cents for anyone recent finding this issue. An ASP MVC project I had manually moved to a subfolder in my solution and then removed and readded to the solution, using Visual Studio 2017, was giving the error mentioned. Moving the "lib" and "packages" folders to the root of the same subfolder as the MVC project fixed my issue.
It should be noted that you can call key()
on any array to find the current key its on. As you can guess current()
will return the current value and next()
will move the array's pointer to the next element.
#!/usr/bin/env python
import smtplib
class Gmail(object):
def __init__(self, email, password):
self.email = email
self.password = password
self.server = 'smtp.gmail.com'
self.port = 587
session = smtplib.SMTP(self.server, self.port)
session.ehlo()
session.starttls()
session.ehlo
session.login(self.email, self.password)
self.session = session
def send_message(self, subject, body):
''' This must be removed '''
headers = [
"From: " + self.email,
"Subject: " + subject,
"To: " + self.email,
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
self.session.sendmail(
self.email,
self.email,
headers + "\r\n\r\n" + body)
gm = Gmail('Your Email', 'Password')
gm.send_message('Subject', 'Message')
Each time I recompiled to local host while developing it took several minutes. It was terribly frustrating. After trying umpteen fixes including putting it all on an SSD. I found what really worked. I created a ramdisk and put the whole project in it. Recompiles to local host are now under ten seconds. Perhaps not elegant but it really worked.
First, let's see what each function does:
regexObject.test( String )
Executes the search for a match between a regular expression and a specified string. Returns true or false.
string.match( RegExp )
Used to retrieve the matches when matching a string against a regular expression. Returns an array with the matches or
null
if there are none.
Since null
evaluates to false
,
if ( string.match(regex) ) {
// There was a match.
} else {
// No match.
}
Is there any difference regarding performance?
Yes. I found this short note in the MDN site:
If you need to know if a string matches a regular expression regexp, use regexp.test(string).
Is the difference significant?
The answer once more is YES! This jsPerf I put together shows the difference is ~30% - ~60% depending on the browser:
Use .test
if you want a faster boolean check. Use .match
to retrieve all matches when using the g
global flag.
Create a linked server to your document
http://www.excel-sql-server.com/excel-import-to-sql-server-using-linked-servers.htm
Then use ordinary INSERT or SELECT INTO. If you want to get fancy, you can use ADO.NET's SqlBulkCopy, which takes just about any data source that you can get a DataReader from and is pretty quick on insert, although the reading of the data won't be esp fast.
You could also take the time to transform an excel spreadsheet into a text delimited file or other bcp supported format and then use BCP.
1) What is the difference between awk and sed ?
Both are tools that transform text. BUT awk can do more things besides just manipulating text. Its a programming language by itself with most of the things you learn in programming, like arrays, loops, if/else flow control etc You can "program" in sed as well, but you won't want to maintain the code written in it.
2) What kind of application are best use cases for sed and awk tools ?
Conclusion: Use sed for very simple text parsing. Anything beyond that, awk is better. In fact, you can ditch sed altogether and just use awk. Since their functions overlap and awk can do more, just use awk. You will reduce your learning curve as well.
Looking at this MSDN Forum Posting it suggests comparing the Cell's value with Cell.TrueValue.
So going by its example your code should looks something like this:(this is completely untested)
Edit: it seems that the Default for Cell.TrueValue for an Unbound DataGridViewCheckBox is null you will need to set it in the Column definition.
private void chkItems_CheckedChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
if (chk.Value == chk.TrueValue)
{
chk.Value = chk.FalseValue;
}
else
{
chk.Value = chk.TrueValue;
}
}
}
This code is working note setting the TrueValue and FalseValue in the Constructor plus also checking for null:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn();
CheckboxColumn.TrueValue = true;
CheckboxColumn.FalseValue = false;
CheckboxColumn.Width = 100;
dataGridView1.Columns.Add(CheckboxColumn);
dataGridView1.Rows.Add(4);
}
private void chkItems_CheckedChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
if (chk.Value == chk.FalseValue || chk.Value == null)
{
chk.Value = chk.TrueValue;
}
else
{
chk.Value = chk.FalseValue;
}
}
dataGridView1.EndEdit();
}
}
do the client machines have python loaded? if so, I'm doing this with psexec
On my local machine, I use subprocess in my .py file to call a command line.
import subprocess
subprocess.call("psexec {server} -c {}")
the -c copies the file to the server so i can run any executable file (which in your case could be a .bat full of connection tests or your .py file from above).
You were setting BCC but then overwriting the variable with the FROM
$to = "[email protected]";
$subject .= "".$emailSubject."";
$headers .= "Bcc: ".$emailList."\r\n";
$headers .= "From: [email protected]\r\n" .
"X-Mailer: php";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= 'THE MESSAGE FROM THE FORM';
if (mail($to, $subject, $message, $headers)) {
$sent = "Your email was sent!";
} else {
$sent = ("Error sending email.");
}
Have a look at the shutil
package, especially rmtree
and copytree
. You can check if a file / path exists with os.paths.exists(<path>)
.
import shutil
import os
def copy_and_overwrite(from_path, to_path):
if os.path.exists(to_path):
shutil.rmtree(to_path)
shutil.copytree(from_path, to_path)
Vincent was right about copytree
not working, if dirs already exist. So distutils
is the nicer version. Below is a fixed version of shutil.copytree
. It's basically copied 1-1, except the first os.makedirs()
put behind an if-else-construct:
import os
from shutil import *
def copytree(src, dst, symlinks=False, ignore=None):
names = os.listdir(src)
if ignore is not None:
ignored_names = ignore(src, names)
else:
ignored_names = set()
if not os.path.isdir(dst): # This one line does the trick
os.makedirs(dst)
errors = []
for name in names:
if name in ignored_names:
continue
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
elif os.path.isdir(srcname):
copytree(srcname, dstname, symlinks, ignore)
else:
# Will raise a SpecialFileError for unsupported file types
copy2(srcname, dstname)
# catch the Error from the recursive copytree so that we can
# continue with other files
except Error, err:
errors.extend(err.args[0])
except EnvironmentError, why:
errors.append((srcname, dstname, str(why)))
try:
copystat(src, dst)
except OSError, why:
if WindowsError is not None and isinstance(why, WindowsError):
# Copying file access times may fail on Windows
pass
else:
errors.extend((src, dst, str(why)))
if errors:
raise Error, errors
As eaon21 and monkey said, source map files basically turn minified code into its unminified version for debugging.
You can find the .map files here. Just add them into the same directory as the minified js files and it'll stop complaining. The reason they get fetched is the
/*
//@ sourceMappingURL=angular.min.js.map
*/
at the end of angular.min.js. If you don't want to add the .map files you can remove those lines and it'll stop the fetch attempt, but if you plan on debugging it's always good to keep the source maps linked.
This worked for me:
<script>
function sel_file() {
$("input[name=userfile]").trigger('click');
}
</script>
<input type="file" name="userfile" id="userfile" />
<a href="javascript:sel_file();">Click</a>
BEST solution if you ask me is this. This will save the file with the file name of your choice and automatically in HTML or in TXT at your choice with buttons.
Example:
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' +
encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
}
function addTextHTML()
{
document.addtext.name.value = document.addtext.name.value + ".html"
}
function addTextTXT()
{
document.addtext.name.value = document.addtext.name.value + ".txt"
}
_x000D_
<html>
<head></head>
<body>
<form name="addtext" onsubmit="download(this['name'].value, this['text'].value)">
<textarea rows="10" cols="70" name="text" placeholder="Type your text here:"></textarea>
<br>
<input type="text" name="name" value="" placeholder="File Name">
<input type="submit" onClick="addTextHTML();" value="Save As HTML">
<input type="submit" onClick="addTexttxt();" value="Save As TXT">
</form>
</body>
</html>
_x000D_
The .cpp
file is configured to use precompiled header, therefore it must be included first (before iostream). For Visual Studio, it's name is usually "stdafx.h".
If there are no stdafx* files in your project, you need to go to this file's options and set it as “Not using precompiled headers”.
How about this?
List<string> monValues = Application["mondayValues"] as List<string>;
int sum = monValues.ConvertAll(Convert.ToInt32).Sum();
To fix your code you can simply change [Cov]
to Cov.values
, the first parameter of pd.DataFrame
will become a multi-dimensional numpy
array:
Cov = pd.read_csv("path/to/file.txt", sep='\t')
Frame=pd.DataFrame(Cov.values, columns = ["Sequence", "Start", "End", "Coverage"])
Frame.to_csv("path/to/file.txt", sep='\t')
But the smartest solution still is use pd.read_excel
with header=None
and names=columns_list
.
Use on-the-fly conversion to std::bitset
. No temporary variables, no loops, no functions, no macros.
#include <iostream>
#include <bitset>
int main() {
int a = -58, b = a>>3, c = -315;
std::cout << "a = " << std::bitset<8>(a) << std::endl;
std::cout << "b = " << std::bitset<8>(b) << std::endl;
std::cout << "c = " << std::bitset<16>(c) << std::endl;
}
Prints:
a = 11000110
b = 11111000
c = 1111111011000101
Queue
is an interface in java, you could not do that.
try:
Queue<Integer> Q = new LinkedList<Integer>();
I've spent the last few months messing around with Gemfiles and Gemfile.locks a lot whilst building an automated dependency update tool1. The below is far from definitive, but it's a good starting point for understanding the Gemfile.lock format. You might also want to check out the source code for Bundler's lockfile parser.
You'll find the following headings in a lockfile generated by Bundler 1.x:
GEM (optional but very common)
These are dependencies sourced from a Rubygems server. That may be the main Rubygems index, at Rubygems.org, or it may be a custom index, such as those available from Gemfury and others. Within this section you'll see:
remote:
one or more lines specifying the location of the Rubygems index(es)specs:
a list of dependencies, with their version number, and the constraints on any subdependenciesGIT (optional)
These are dependencies sourced from a given git remote. You'll see a different one of these sections for each git remote, and within each section you'll see:
remote:
the git remote. E.g., [email protected]:rails/rails
revision:
the commit reference the Gemfile.lock is locked totag:
(optional) the tag specified in the Gemfilespecs:
the git dependency found at this remote, with its version number, and the constraints on any subdependenciesPATH (optional)
These are dependencies sourced from a given path
, provided in the Gemfile. You'll see a different one of these sections for each path dependency, and within each section you'll see:
remote:
the path. E.g., plugins/vendored-dependency
specs:
the git dependency found at this remote, with its version number, and the constraints on any subdependenciesPLATFORMS
The Ruby platform the Gemfile.lock was generated against. If any dependencies in the Gemfile specify a platform then they will only be included in the Gemfile.lock when the lockfile is generated on that platform (e.g., through an install).
DEPENDENCIES
A list of the dependencies which are specified in the Gemfile
, along with the version constraint specified there.
Dependencies specified with a source other than the main Rubygems index (e.g., git dependencies, path-based, dependencies) have a !
which means they are "pinned" to that source2 (although one must sometimes look in the Gemfile to determine in).
RUBY VERSION (optional)
The Ruby version specified in the Gemfile, when this Gemfile.lock was created. If a Ruby version is specified in a .ruby_version
file instead this section will not be present (as Bundler will consider the Gemfile / Gemfile.lock agnostic to the installer's Ruby version).
BUNDLED WITH (Bundler >= v1.10.x)
The version of Bundler used to create the Gemfile.lock. Used to remind installers to update their version of Bundler, if it is older than the version that created the file.
PLUGIN SOURCE (optional and very rare)
In theory, a Gemfile can specify Bundler plugins, as well as gems3, which would then be listed here. In practice, I'm not aware of any available plugins, as of July 2017. This part of Bundler is still under active development!
You do this in 3 different ways:
Before you do an INSERT
, always issue a BEGIN;
statement. This will turn off autocommits. You will need to do a COMMIT;
once you want your data to be persisted in the database.
Use autocommit=0;
every time you instantiate a database connection.
For a global setting, add a autocommit=0
variable in your my.cnf
configuration file in MySQL.
function get_time($time) {
$duration = $time / 1000;
$hours = floor($duration / 3600);
$minutes = floor(($duration / 60) % 60);
$seconds = $duration % 60;
if ($hours != 0)
echo "$hours:$minutes:$seconds";
else
echo "$minutes:$seconds";
}
get_time('1119241');
Must be used convert, not cast:
SELECT
CONVERT(varchar(50), N'æøåáälcçcédnoöruýtžš')
COLLATE Cyrillic_General_CI_AI
Use composition:
class ClassC
{
public ClassA A { get; set; }
public ClassB B { get; set; }
public C (ClassA a, ClassB b)
{
this.A = a;
this.B = b;
}
}
Then you can call C.A.DoA()
. You also can change the properties to an interface or abstract class, like public InterfaceA A
or public AbstractClassA A
.
Under Windows 7, open the Event Viewer. You can do this the way Gishu suggested for XP, typing eventvwr
from the command line, or by opening the Control Panel, selecting System and Security, then Administrative Tools and finally Event Viewer. It may require UAC approval or an admin password.
In the left pane, expand Windows Logs and then System. You can filter the logs with Filter Current Log... from the Actions pane on the right and selecting "Service Control Manager." Or, depending on why you want this information, you might just need to look through the Error entries.
The actual log entry pane (not shown) is pretty user-friendly and self-explanatory. You'll be looking for messages like the following:
"The Praxco Assistant service entered the stopped state."
"The Windows Image Acquisition (WIA) service entered the running state."
"The MySQL service terminated unexpectedly. It has done this 3 time(s)."
and the version to work on the array type:
select
array_to_string(
array(select distinct unnest(zip_codes) from table),
', '
);
It is more about personalize your textField but anyways I'll share this code got from another page and made it a little better:
import UIKit
extension UITextField {
func setBottomLine(borderColor: UIColor, fontColor: UIColor, placeHolderColor:UIColor, placeHolder: String) {
self.borderStyle = UITextBorderStyle.none
self.backgroundColor = UIColor.clear
let borderLine = UIView()
let height = 1.0
borderLine.frame = CGRect(x: 0, y: Double(self.frame.height) - height, width: Double(self.frame.width), height: height)
self.textColor = fontColor
borderLine.backgroundColor = borderColor
self.addSubview(borderLine)
self.attributedPlaceholder = NSAttributedString(
string: placeHolder,
attributes: [NSAttributedStringKey.foregroundColor: placeHolderColor]
)
}
}
And you can use it like this:
self.textField.setBottomLine(borderColor: lineColor, fontColor: fontColor, placeHolderColor: placeHolderColor, placeHolder: placeHolder)
Knowing that you have an UITextField
connected to a ViewController
.
Source: http://codepany.com/blog/swift-3-custom-uitextfield-with-single-line-input/
I had the same issue. Ran 5 or 6 hours of researches. A simple solution seems to be working. I just had to convert my folder to application from iis. It worked fine. (this was a scenario where I had done a migration from server 2003 to server 2008 R2)
(1) Open IIS and select the website and the appropriate folder that needs to be converted. Right-click and select Convert to Application.
WORKAROUND:
The possible workaround is modify your project's platform from 'Any CPU' to 'X86' (in Project's Properties, Build/Platform's Target)
ROOTCAUSE
The VSS Interop is a managed assembly using 32-bit Framework and the dll contains a 32-bit COM object. If you run this COM dll in 64 bit environment, you will get the error message.
In the first instance you are trying to create what is called a jagged array.
double[][] ServicePoint = new double[10][9].
The above statement would have worked if it was defined like below.
double[][] ServicePoint = new double[10][]
what this means is you are creating an array of size 10 ,that can store 10 differently sized arrays inside it.In simple terms an Array of arrays.see the below image,which signifies a jagged array.
http://msdn.microsoft.com/en-us/library/2s05feca(v=vs.80).aspx
The second one is basically a two dimensional array and the syntax is correct and acceptable.
double[,] ServicePoint = new double[10,9];//<-ok (2)
And to access or modify a two dimensional array you have to pass both the dimensions,but in your case you are passing just a single dimension,thats why the error
Correct usage would be
ServicePoint[0][2]
,Refers to an item on the first row ,third column.
Pictorial rep of your two dimensional array
Go to the first line from which you would like to delete, and press the keys dG
Declaration here
fileprivate weak var textView: UITextView!
Call your setupview here
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
}
Setup here
fileprivate func setupViews() {
let textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.text = "your text here"
textView.font = UIFont.poppinsMedium(size: 14)
textView.textColor = UIColor.brownishGrey
textView.textAlignment = .left
textView.isEditable = false
textView.isScrollEnabled = false
textView.textContainerInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
self.view.addSubview(textView)
self.textView = textView
setupConstraints()
}
Setup constraints here
fileprivate func setupConstraints() {
NSLayoutConstraint.activate([
textView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
textView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20),
textView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20),
textView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20),
textView.heightAnchor.constraint(greaterThanOrEqualToConstant: 150),
])
}
i'd use a simple one line comparisant for these use cases
$username = trim($_POST['userName'])?:'Anonymous';
This is for the use case you are certain error logging is off so you don't get a warning that the variable isn't initialised.
this is the paranoid version:
$username = !empty(trim(isset($_POST['userName'])?$_POST['userName']:''))?$_POST['userName']:'Anonymous';
This implements a check if the $_POST
variable is set. before accessing it.
.flexContainer {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.inputField {_x000D_
flex: 1;_x000D_
}
_x000D_
<div class="flexContainer">_x000D_
<input type="password" class="inputField">_x000D_
<button type="submit"><img src="arrow.png" alt="Arrow Icon"></button>_x000D_
</div>
_x000D_
You are trying to decode an object that is already decoded. You have a str
, there is no need to decode from UTF-8 anymore.
Simply drop the .decode('utf-8')
part:
header_data = data[1][0][1]
As for your fetch()
call, you are explicitly asking for just the first message. Use a range if you want to retrieve more messages. See the documentation:
The message_set options to commands below is a string specifying one or more messages to be acted upon. It may be a simple message number (
'1'
), a range of message numbers ('2:4'
), or a group of non-contiguous ranges separated by commas ('1:3,6:9'
). A range can contain an asterisk to indicate an infinite upper bound ('3:*'
).
I had this problem with an existing Mongodb setup. I'm still not sure why it happened, but for some reason the Mongod process couldn't find the mongod.config file. Because it could not find the config file it tried to find the DB files in /data/db, a folder that didn't exist. However, the config file was still available so I made sure the process has permissions to the config file and run the mongod process with the --config flag as follows:
mongod --config /etc/mongod.conf
In the config file itself I had this setting:
storage:
dbPath: /var/lib/mongodb
And this is how the process could find the real DB folder again.
Copy Database Dump File at (Windows PC) D:\xampp\mysql\bin
mysql -h localhost -u root Databasename <@data11.sql
We can count from many ways for the occurrence of substring:-
public class Test1 {
public static void main(String args[]) {
String st = "abcdsfgh yfhf hghj gjgjhbn hgkhmn abc hadslfahsd abcioh abc a ";
count(st, 0, "a".length());
}
public static void count(String trim, int i, int length) {
if (trim.contains("a")) {
trim = trim.substring(trim.indexOf("a") + length);
count(trim, i + 1, length);
} else {
System.out.println(i);
}
}
public static void countMethod2() {
int index = 0, count = 0;
String inputString = "mynameiskhanMYlaptopnameishclMYsirnameisjasaiwalmyfrontnameisvishal".toLowerCase();
String subString = "my".toLowerCase();
while (index != -1) {
index = inputString.indexOf(subString, index);
if (index != -1) {
count++;
index += subString.length();
}
}
System.out.print(count);
}}
As a picture is worth a thousand words..
When you find the IIS6 manager (I have found that searching for IIS may return 2 results) go to the SMTP server properties then 'Access' then press the relay button.
Then you can either select all or only allow certain ip's like 127.0.0.1
After executing the below regex, your answer is in the first capture.
/^(.*?)\.txt/
Script grouping is counterproductive, you should load them in parallel using something like http://yepnopejs.com/ or http://headjs.com
Simplified version:
Date.prototype.clone = function () {
return new Date(this.getTime());
}
To follow up on the answer by user183038, here is a shell script to batch rename all xlsx files to csv while preserving the file names. The xlsx2csv tool needs to be installed prior to running.
for i in *.xlsx;
do
filename=$(basename "$i" .xlsx);
outext=".csv"
xlsx2csv $i $filename$outext
done
#include <boost/algorithm/string.hpp>
#include <string>
std::string str = "Hello World";
boost::to_upper(str);
std::string newstr = boost::to_upper_copy<std::string>("Hello World");
What exactly do you want to know? ActiveRecord has methods that serialize records into JSON. For instance, open up your rails console and enter ModelName.all.to_json
and you will see JSON output. render :json
essentially calls to_json
and returns the result to the browser with the correct headers. This is useful for AJAX calls in JavaScript where you want to return JavaScript objects to use. Additionally, you can use the callback
option to specify the name of the callback you would like to call via JSONP.
For instance, lets say we have a User
model that looks like this: {name: 'Max', email:' [email protected]'}
We also have a controller that looks like this:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
render json: @user
end
end
Now, if we do an AJAX call using jQuery like this:
$.ajax({
type: "GET",
url: "/users/5",
dataType: "json",
success: function(data){
alert(data.name) // Will alert Max
}
});
As you can see, we managed to get the User with id 5 from our rails app and use it in our JavaScript code because it was returned as a JSON object. The callback option just calls a JavaScript function of the named passed with the JSON object as the first and only argument.
To give an example of the callback
option, take a look at the following:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
render json: @user, callback: "testFunction"
end
end
Now we can crate a JSONP request as follows:
function testFunction(data) {
alert(data.name); // Will alert Max
};
var script = document.createElement("script");
script.src = "/users/5";
document.getElementsByTagName("head")[0].appendChild(script);
The motivation for using such a callback is typically to circumvent the browser protections that limit cross origin resource sharing (CORS). JSONP isn't used that much anymore, however, because other techniques exist for circumventing CORS that are safer and easier.
I currently use a very easy implementation, which does not require to use converters or special classes. The code I use is the following:
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
DialogHelper.dismiss();
if (response.isSuccessful()) {
// Do your success stuff...
} else {
try {
JSONObject jObjError = new JSONObject(response.errorBody().string());
Toast.makeText(getContext(), jObjError.getJSONObject("error").getString("message"), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
new Double(object.toString());
But it seems weird to me that you're going from an Object to a Double. You should have a better idea what class of object you're starting with before attempting a conversion. You might have a bit of a code quality problem there.
Note that this is a conversion, not casting.
Something else to consider when this type of error is encountered:
I was running into this error message and found this post helpful. Turns out in my case I had overridden an __init__()
where there was object inheritance.
The inherited example is rather long, so I'll skip to a more simple example that doesn't use inheritance:
class MyBadInitClass:
def ___init__(self, name):
self.name = name
def name_foo(self, arg):
print(self)
print(arg)
print("My name is", self.name)
class MyNewClass:
def new_foo(self, arg):
print(self)
print(arg)
my_new_object = MyNewClass()
my_new_object.new_foo("NewFoo")
my_bad_init_object = MyBadInitClass(name="Test Name")
my_bad_init_object.name_foo("name foo")
Result is:
<__main__.MyNewClass object at 0x033C48D0>
NewFoo
Traceback (most recent call last):
File "C:/Users/Orange/PycharmProjects/Chapter9/bad_init_example.py", line 41, in <module>
my_bad_init_object = MyBadInitClass(name="Test Name")
TypeError: object() takes no parameters
PyCharm didn't catch this typo. Nor did Notepad++ (other editors/IDE's might).
Granted, this is a "takes no parameters" TypeError, it isn't much different than "got two" when expecting one, in terms of object initialization in Python.
Addressing the topic: An overloading initializer will be used if syntactically correct, but if not it will be ignored and the built-in used instead. The object won't expect/handle this and the error is thrown.
In the case of the sytax error: The fix is simple, just edit the custom init statement:
def __init__(self, name):
self.name = name
I am also faced the same issue
use this code:
// notice string() call
String resStr = response.body().string();
JSONObject json = new JSONObject(resStr);
it definitely works
In a project, I actually have some heading fixed to the bottom of the screen on page load (it's a drawing app so the heading is at the bottom to give maximum space to the canvas element on wide viewport).
I needed the heading to become 'absolute' when it reaches the footer on scroll, since I don't want the heading over the footer (heading colour is same as footer background colour).
I took the oldest response on here (edited by Gearge Millo) and that code snippet worked for my use-case. With some playing around I got this working. Now the fixed heading sits beautifully above the footer once it reaches the footer.
Just thought I'd share my use-case and how it worked, and say thank you! The app: http://joefalconer.com/web_projects/drawingapp/index.html
/* CSS */
@media screen and (min-width: 1100px) {
#heading {
height: 80px;
width: 100%;
position: absolute; /* heading is 'absolute' on page load. DOESN'T WORK if I have this on 'fixed' */
bottom: 0;
}
}
// jQuery
// Stop the fixed heading from scrolling over the footer
$.fn.followTo = function (pos) {
var $this = this,
$window = $(window);
$window.scroll(function (e) {
if ($window.scrollTop() > pos) {
$this.css( { position: 'absolute', bottom: '-180px' } );
} else {
$this.css( { position: 'fixed', bottom: '0' } );
}
});
};
// This behaviour is only needed for wide view ports
if ( $('#heading').css("position") === "absolute" ) {
$('#heading').followTo(180);
}
It is best to also quote $1:
sed -i.bak 's/[[:blank:]]*$//' "$1"
I got this on Firefox (FF58). I fixed this with:
dom.moduleScripts.enabled
in about:config
Source: Import page on mozilla (See Browser compatibility)
type="module"
to your script tag where you import the js file<script type="module" src="appthatimports.js"></script>
./
, /
, ../
or http://
before)import * from "./mylib.js"
For more examples, this blog post is good.
Note in Guzzle V6.0+, another source of getting the following error may be incorrect use of JSON as an array:
Passing in the "body" request option as an array to send a POST request has been deprecated. Please use the "form_params" request option to send a application/x-www-form-urlencoded request, or a the "multipart" request option to send a multipart/form-data request.
Incorrect:
$response = $client->post('http://example.com/api', [
'body' => [
'name' => 'Example name',
]
])
Correct:
$response = $client->post('http://example.com/api', [
'json' => [
'name' => 'Example name',
]
])
Correct:
$response = $client->post('http://example.com/api', [
'headers' => ['Content-Type' => 'application/json'],
'body' => json_encode([
'name' => 'Example name',
])
])
This is a very late response, but adds some detail on the previous answers
When it comes to calling static methods in PHP from another static method on the same class, it is important to differentiate between self
and the class name.
Take for instance this code:
class static_test_class {
public static function test() {
echo "Original class\n";
}
public static function run($use_self) {
if($use_self) {
self::test();
} else {
$class = get_called_class();
$class::test();
}
}
}
class extended_static_test_class extends static_test_class {
public static function test() {
echo "Extended class\n";
}
}
extended_static_test_class::run(true);
extended_static_test_class::run(false);
The output of this code is:
Original class
Extended class
This is because self
refers to the class the code is in, rather than the class of the code it is being called from.
If you want to use a method defined on a class which inherits the original class, you need to use something like:
$class = get_called_class();
$class::function_name();
I found a way. It's a bit hacky but works.
vm.$set("x",0);
vm.$delete("x");
Where vm
is your view-model object, and x
is a non-existent variable.
Vue.js will complain about this in the console log but it does trigger a refresh for all data. Tested with version 1.0.26.
If you want some element to contain a value that is HTML, take a look at ngBindHtmlUnsafe.
If you want to style options in a native select, no it is not possible.
First of all, your description is misleading. Double
is a floating point data type. You presumably want to pad your digits with leading zeros in a string. The following code does that:
$s = sprintf('%02d', $digit);
For more information, refer to the documentation of sprintf
.
Agreed with part of @Jeffrey Fox's answer:
max-age=0, must-revalidate and no-cache aren't exactly identical.
Not agreed with this part:
With no-cache, it would just show the cached content, which would be probably preferred by the user (better to have something stale than nothing at all).
What should implementations do when cache-control: no-cache
revalidation failed is just not specified in the RFC document. It's all up to implementations. They may throw a 504 error like cache-control: must-revalidate
or just serve a stale copy from cache.
try this for hide
$('#table_id').DataTable({
"info": false
});
and try this for change label
$('#table_id').DataTable({
"oLanguage": {
"sInfo" : "Showing _START_ to _END_ of _TOTAL_ entries",// text you want show for info section
},
});
Copy and paste the following into a new .htaccess
file and place it on your website's root folder :
php_flag display_errors on
php_flag display_startup_errors on
Errors will be shown directly in your page.
That's the best way to debug quickly but don't use it for long time because it could be a security breach.
Here's another solution that uses some of VBA's built in date functions and stores all the date data in an array for comparison, which may give better performance if you get a lot of data:
Public Sub MoveData(MonthNum As Integer, FromSheet As Worksheet, ToSheet As Worksheet)
Const DateCol = "A" 'column where dates are store
Const DestCol = "A" 'destination column where dates are stored. We use this column to find the last populated row in ToSheet
Const FirstRow = 2 'first row where date data is stored
'Copy range of values to Dates array
Dates = FromSheet.Range(DateCol & CStr(FirstRow) & ":" & DateCol & CStr(FromSheet.Range(DateCol & CStr(FromSheet.Rows.Count)).End(xlUp).Row)).Value
Dim i As Integer
For i = LBound(Dates) To UBound(Dates)
If IsDate(Dates(i, 1)) Then
If Month(CDate(Dates(i, 1))) = MonthNum Then
Dim CurrRow As Long
'get the current row number in the worksheet
CurrRow = FirstRow + i - 1
Dim DestRow As Long
'get the destination row
DestRow = ToSheet.Range(DestCol & CStr(ToSheet.Rows.Count)).End(xlUp).Row + 1
'copy row CurrRow in FromSheet to row DestRow in ToSheet
FromSheet.Range(CStr(CurrRow) & ":" & CStr(CurrRow)).Copy ToSheet.Range(DestCol & CStr(DestRow))
End If
End If
Next i
End Sub
You can use dtype=np.int64
instead of dtype=int
You can write queries like this in SQL Server:
--each [0-9] matches a single digit, this would match 5xx
SELECT * FROM YourTable WHERE SomeField LIKE '5[0-9][0-9]'
you must put object in your JSX, It`s easy way to do this just see my simple code here:
const link = [
{
name: "Cold Drink",
link: "/coldDrink"
},
{
name: "Hot Drink",
link: "/HotDrink"
},
{ name: "chease Cake", link: "/CheaseCake" } ]; and you must map this array in your code with simple object see this code :
const links = (this.props.link);
{links.map((item, i) => (
<li key={i}>
<Link to={item.link}>{item.name}</Link>
</li>
))}
I hope this answer will be helpful for you ...:)
Here is something that might help you doing it. I managed to do it in two iterations.
private static IEnumerable<string> GetAllNonEmptyDirectories(string path)
{
var directories =
Directory.EnumerateDirectories(path, "*.*", SearchOption.AllDirectories)
.ToList();
var directoryList =
(from directory in directories
let isEmpty = Directory.GetFiles(directory, "*.*", SearchOption.AllDirectories).Length == 0
where !isEmpty select directory)
.ToList();
return directoryList.ToList();
}
You can use CFArray instead of NSArray. Here is an article explaining how.
CFMutableArrayRef ar = CFArrayCreateMutable(NULL, 0, NULL);
for (NSUInteger i = 0; i < 1000; i++)
{
CFArrayAppendValue(ar, (void*)i);
}
CFRelease(ar); /* Releasing the array */
The same applies for the CoreFoundation version of the other containers too.
Wikipedia (or rather, the community on Wikipedia) keeps a pretty good up-to-date list here.
On MAC you can do sout + return
or ?+j
(cmd+j) opens live template suggestions, enter sout
to choose System.out.println();
You need to give the button a name and a value.
No control can be submitted without a name, and the content of a button element is the label, not the value.
<form action="" method="post">
<button name="foo" value="upvote">Upvote</button>
</form>
Try =Year(Now())
and format the cell as General
.
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
(Update: August 2011)
As geofflane mentions in his answer, Java 7 now support named groups.
tchrist points out in the comment that the support is limited.
He details the limitations in his great answer "Java Regex Helper"
Java 7 regex named group support was presented back in September 2010 in Oracle's blog.
In the official release of Java 7, the constructs to support the named capturing group are:
(?<name>capturing text)
to define a named group "name"\k<name>
to backreference a named group "name"${name}
to reference to captured group in Matcher's replacement stringMatcher.group(String name)
to return the captured input subsequence by the given "named group".
Other alternatives for pre-Java 7 were:
(Original answer: Jan 2009, with the next two links now broken)
You can not refer to named group, unless you code your own version of Regex...
That is precisely what Gorbush2 did in this thread.
(limited implementation, as pointed out again by tchrist, as it looks only for ASCII identifiers. tchrist details the limitation as:
only being able to have one named group per same name (which you don’t always have control over!) and not being able to use them for in-regex recursion.
Note: You can find true regex recursion examples in Perl and PCRE regexes, as mentioned in Regexp Power, PCRE specs and Matching Strings with Balanced Parentheses slide)
Example:
String:
"TEST 123"
RegExp:
"(?<login>\\w+) (?<id>\\d+)"
Access
matcher.group(1) ==> TEST
matcher.group("login") ==> TEST
matcher.name(1) ==> login
Replace
matcher.replaceAll("aaaaa_$1_sssss_$2____") ==> aaaaa_TEST_sssss_123____
matcher.replaceAll("aaaaa_${login}_sssss_${id}____") ==> aaaaa_TEST_sssss_123____
(extract from the implementation)
public final class Pattern
implements java.io.Serializable
{
[...]
/**
* Parses a group and returns the head node of a set of nodes that process
* the group. Sometimes a double return system is used where the tail is
* returned in root.
*/
private Node group0() {
boolean capturingGroup = false;
Node head = null;
Node tail = null;
int save = flags;
root = null;
int ch = next();
if (ch == '?') {
ch = skip();
switch (ch) {
case '<': // (?<xxx) look behind or group name
ch = read();
int start = cursor;
[...]
// test forGroupName
int startChar = ch;
while(ASCII.isWord(ch) && ch != '>') ch=read();
if(ch == '>'){
// valid group name
int len = cursor-start;
int[] newtemp = new int[2*(len) + 2];
//System.arraycopy(temp, start, newtemp, 0, len);
StringBuilder name = new StringBuilder();
for(int i = start; i< cursor; i++){
name.append((char)temp[i-1]);
}
// create Named group
head = createGroup(false);
((GroupTail)root).name = name.toString();
capturingGroup = true;
tail = root;
head.next = expr(tail);
break;
}
if you are using PyCharm, when you open or clone the project into the PyCharm it shows an alert and ask you for installing all necessary packages.
Basically, if there is a need to display a sorted collection, please consider using the CollectionViewSource
class: assign ("bind") its Source
property to the source collection — an instance of the ObservableCollection<T>
class.
The idea is that CollectionViewSource
class provides an instance of the CollectionView
class. This is kind of "projection" of the original (source) collection, but with applied sorting, filtering, etc.
References:
WPF 4.5 introduces "Live Shaping" feature for CollectionViewSource
.
References:
If there still a need to sort an instance of the ObservableCollection<T>
class, here is how it can be done.
The ObservableCollection<T>
class itself does not have sort method. But, the collection could be re-created to have items sorted:
// Animals property setter must raise "property changed" event to notify binding clients.
// See INotifyPropertyChanged interface for details.
Animals = new ObservableCollection<string>
{
"Cat", "Dog", "Bear", "Lion", "Mouse",
"Horse", "Rat", "Elephant", "Kangaroo",
"Lizard", "Snake", "Frog", "Fish",
"Butterfly", "Human", "Cow", "Bumble Bee"
};
...
Animals = new ObservableCollection<string>(Animals.OrderBy(i => i));
Please note that OrderBy()
and OrderByDescending()
methods (as other LINQ–extension methods) do not modify the source collection! They instead create a new sequence (i.e. a new instance of the class that implements IEnumerable<T>
interface). Thus, it is necessary to re-create the collection.
we are creating a simple function as
callBackFunction (data, function ( err, response ){
console.log(response)
})
// callbackfunction
function callBackFuntion (data, callback){
//write your logic and return your result as
callback("",result) //if not error
callback(error, "") //if error
}
Guava has a method to do this for you: double[] Doubles.toArray(Collection<Double>)
This isn't necessarily going to be any faster than just looping through the Collection
and adding each Double
object to the array, but it's a lot less for you to write.
Another aproach is:
let result = { ...item, location : { ...response } }
But Object spread isn't yet standardized.
May also be helpful: https://stackoverflow.com/a/32926019/5341953
$json empty
public function deleteUser($extid)
{
$path = "/rest/user/".$extid."/;token=".$this->__token;
$result = $this->curl_req($path,"**$json**","DELETE");
return $result;
}
Simply use the below code for the fragment.
@Override
public void onOtherButtonClick(ActionSheet actionSheet, int index) {
if (index == 1)
{
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), 1);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 1) {
if (requestCode == 1) {
Uri selectedImageUri = data.getData();
//selectedImagePath = getPath(selectedImageUri);
}
}
}
onActivityResult will call without calling its parent.
I was getting the same error. For Java version 7, following is working for me.
java.lang.System.setProperty("https.protocols", "TLSv1.2");
Here is an another way find value index in complex array in javascript. Hope help somebody indeed. Let us assume we have a JavaScript array as following,
var studentsArray =
[
{
"rollnumber": 1,
"name": "dj",
"subject": "physics"
},
{
"rollnumber": 2,
"name": "tanmay",
"subject": "biology"
},
{
"rollnumber": 3,
"name": "amit",
"subject": "chemistry"
},
];
Now if we have a requirement to select a particular object in the array. Let us assume that we want to find index of student with name Tanmay.
We can do that by iterating through the array and comparing value at the given key.
function functiontofindIndexByKeyValue(arraytosearch, key, valuetosearch) {
for (var i = 0; i < arraytosearch.length; i++) {
if (arraytosearch[i][key] == valuetosearch) {
return i;
}
}
return null;
}
You can use the function to find index of a particular element as below,
var index = functiontofindIndexByKeyValue(studentsArray, "name", "tanmay");
alert(index);
As mentioned here (in French), this can happen when you have two versions of R installed on your computer. Uninstall the oldest one, then try your package installation again! It worked fine for me.
math.sqrt
is the C implementation of square root and is therefore different from using the **
operator which implements Python's built-in pow
function. Thus, using math.sqrt
actually gives a different answer than using the **
operator and there is indeed a computational reason to prefer numpy
or math
module implementation over the built-in. Specifically the sqrt functions are probably implemented in the most efficient way possible whereas **
operates over a large number of bases and exponents and is probably unoptimized for the specific case of square root. On the other hand, the built-in pow
function handles a few extra cases like "complex numbers, unbounded integer powers, and modular exponentiation".
See this Stack Overflow question for more information on the difference between **
and math.sqrt
.
In terms of which is more "Pythonic", I think we need to discuss the very definition of that word. From the official Python glossary, it states that a piece of code or idea is Pythonic if it "closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages." In every single other language I can think of, there is some math module with basic square root functions. However there are languages that lack a power operator like **
e.g. C++. So **
is probably more Pythonic, but whether or not it's objectively better depends on the use case.
List<Card> list = new ArrayList<Card>(Arrays.asList(hand));
The R class is Java code auto-generated from your XML files (UI layout, internationalization strings, etc.) If the code used to be working before (as it seems it is), you need to tell your IDE to regenerate these files somehow:
If you're going to access your local computer (or any computer) using UNC, you'll need to setup a share. If you haven't already setup a share, you could use the default administrative shares. Example:
\\localhost\c$\my_dir
... accesses a folder called "my_dir" via UNC on your C: drive. By default all the hard drives on your machine are shared with hidden shares like c$, d$, etc.
Or, alternatively, you could use Operator module. More detailed information is here Python docs
import operator
import numpy as np
import pandas as pd
np.random.seed(0)
df = pd.DataFrame(np.random.randn(5,3), columns=list('ABC'))
df.loc[operator.or_(df.C > 0.25, df.C < -0.25)]
A B C
0 1.764052 0.400157 0.978738
1 2.240893 1.867558 -0.977278
3 0.410599 0.144044 1.454274
4 0.761038 0.121675 0.4438
After you correct the possible dmp file problem, this is a way to ensure that the schema is remapped and imported appropriately. This will also ensure that the tablespace will change also, if needed:
impdp system/<password> SCHEMAS=user1 remap_schema=user1:user2 \
remap_tablespace=user1:user2 directory=EXPORTDIR \
dumpfile=user1.dmp logfile=E:\Data\user1.log
EXPORTDIR must be defined in oracle as a directory as the system user
create or replace directory EXPORTDIR as 'E:\Data';
grant read, write on directory EXPORTDIR to user2;
This is possible in Java 9.
Stream.generate(() -> null)
.takeWhile(x -> iterator.hasNext())
.map(n -> iterator.next())
.forEach(System.out::println);
Try BeanComparator from Apache Commons.
import org.apache.commons.beanutils.BeanComparator;
BeanComparator fieldComparator = new BeanComparator("fruitName");
Collections.sort(fruits, fieldComparator);
LIMIT allow you to skip any number of rows. It has two parameters, and first of them - how many rows to skip
Judging from the error message the value of i was the empty string when you executed it, not 0.
If you are seeing(3 messages are hidden by filters. Show all messages.) then click on show all message link in Chrome dev tool console.
Because if this option enabled by mistake the console.log("")
message will show but this will in in hidden state.
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
.clearfix
is defined in less/mixins.less
. Right above its definition is a comment with a link to this article:
The article explains how it all works.
UPDATE: Yes, link-only answers are bad. I knew this even at the time that I posted this answer, but I didn't feel like copying and pasting was OK due to copyright, plagiarism, and what have you. However, I now feel like it's OK since I have linked to the original article. I should also mention the author's name, though, for credit: Nicolas Gallagher. Here is the meat of the article (note that "Thierry’s method" is referring to Thierry Koblentz’s “clearfix reloaded”):
This “micro clearfix” generates pseudo-elements and sets their
display
totable
. This creates an anonymous table-cell and a new block formatting context that means the:before
pseudo-element prevents top-margin collapse. The:after
pseudo-element is used to clear the floats. As a result, there is no need to hide any generated content and the total amount of code needed is reduced.Including the
:before
selector is not necessary to clear the floats, but it prevents top-margins from collapsing in modern browsers. This has two benefits:
It ensures visual consistency with other float containment techniques that create a new block formatting context, e.g.,
overflow:hidden
It ensures visual consistency with IE 6/7 when
zoom:1
is applied.N.B.: There are circumstances in which IE 6/7 will not contain the bottom margins of floats within a new block formatting context. Further details can be found here: Better float containment in IE using CSS expressions.
The use of
content:" "
(note the space in the content string) avoids an Opera bug that creates space around clearfixed elements if thecontenteditable
attribute is also present somewhere in the HTML. Thanks to Sergio Cerrutti for spotting this fix. An alternative fix is to usefont:0/0 a
.Legacy Firefox
Firefox < 3.5 will benefit from using Thierry’s method with the addition of
visibility:hidden
to hide the inserted character. This is because legacy versions of Firefox needcontent:"."
to avoid extra space appearing between thebody
and its first child element, in certain circumstances (e.g., jsfiddle.net/necolas/K538S/.)Alternative float-containment methods that create a new block formatting context, such as applying
overflow:hidden
ordisplay:inline-block
to the container element, will also avoid this behaviour in legacy versions of Firefox.
I had this identical problem, I was using django-rest-knox for authentication tokens. It turns out that nothing was wrong with my fetch method which looked like this:
...
let headers = {"Content-Type": "application/json"};
if (token) {
headers["Authorization"] = `Token ${token}`;
}
return fetch("/api/instruments/", {headers,})
.then(res => {
...
I was running apache.
What solved this problem for me was changing WSGIPassAuthorization
to 'On'
in wsgi.conf
.
I had a Django app deployed on AWS EC2, and I used Elastic Beanstalk to manage my application, so in the django.config
, I did this:
container_commands:
01wsgipass:
command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'
Linux.
$ apt-get install beep
$ python
>>> os.system("beep -f 555 -l 460")
OR
$ beep -f 659 -l 460 -n -f 784 -l 340 -n -f 659 -l 230 -n -f 659 -l 110 -n -f 880 -l 230 -n -f 659 -l 230 -n -f 587 -l 230 -n -f 659 -l 460 -n -f 988 -l 340 -n -f 659 -l 230 -n -f 659 -l 110 -n -f 1047-l 230 -n -f 988 -l 230 -n -f 784 -l 230 -n -f 659 -l 230 -n -f 988 -l 230 -n -f 1318 -l 230 -n -f 659 -l 110 -n -f 587 -l 230 -n -f 587 -l 110 -n -f 494 -l 230 -n -f 740 -l 230 -n -f 659 -l 460
This should work.
k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
k_cleaned = []
for ele in k:
if set(ele) not in [set(x) for x in k_cleaned]:
k_cleaned.append(ele)
print(k_cleaned)
# output: [[1, 2], [4], [5, 6, 2], [3]]
i added both Convert Zero Datetime=True
& Allow Zero Datetime=True
and it works fine
# reassign depth values under 10 to zero
df$depth[df$depth<10] <- 0
(For the columns that are factors, you can only assign values that are factor levels. If you wanted to assign a value that wasn't currently a factor level, you would need to create the additional level first:
levels(df$species) <- c(levels(df$species), "unknown")
df$species[df$depth<10] <- "unknown"
You need to be careful though, You need to setup the EDMX file exactly as it was before deleting it (if you choose the delete/regenerate route), otherwise, you'll have a naming mismatch between your code and the EF generated model (especialy for pluralization and singularization)
Hope this will prevent you some headaches =)
I found a mod_rewrite
solution that works well for both proxied and unproxied servers.
If you are using CloudFlare, AWS Elastic Load Balancing, Heroku, OpenShift or any other Cloud/PaaS solution and you are experiencing redirect loops with normal HTTPS redirects, try the following snippet instead.
RewriteEngine On
# If we receive a forwarded http request from a proxy...
RewriteCond %{HTTP:X-Forwarded-Proto} =http [OR]
# ...or just a plain old http request directly from the client
RewriteCond %{HTTP:X-Forwarded-Proto} =""
RewriteCond %{HTTPS} !=on
# Redirect to https version
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Internet Control Message Protocol
http://en.wikipedia.org/wiki/Internet_Control_Message_Protocol
ICMP is built on top of a bunch of other protocols, so in that sense your TA is correct. However, ping itself is ICMP.
unicode
is meant to handle text. Text is a sequence of code points which may be bigger than a single byte. Text can be encoded in a specific encoding to represent the text as raw bytes(e.g. utf-8
, latin-1
...).
Note that unicode
is not encoded! The internal representation used by python is an implementation detail, and you shouldn't care about it as long as it is able to represent the code points you want.
On the contrary str
in Python 2 is a plain sequence of bytes. It does not represent text!
You can think of unicode
as a general representation of some text, which can be encoded in many different ways into a sequence of binary data represented via str
.
Note: In Python 3, unicode
was renamed to str
and there is a new bytes
type for a plain sequence of bytes.
Some differences that you can see:
>>> len(u'à') # a single code point
1
>>> len('à') # by default utf-8 -> takes two bytes
2
>>> len(u'à'.encode('utf-8'))
2
>>> len(u'à'.encode('latin1')) # in latin1 it takes one byte
1
>>> print u'à'.encode('utf-8') # terminal encoding is utf-8
à
>>> print u'à'.encode('latin1') # it cannot understand the latin1 byte
?
Note that using str
you have a lower-level control on the single bytes of a specific encoding representation, while using unicode
you can only control at the code-point level. For example you can do:
>>> 'àèìòù'
'\xc3\xa0\xc3\xa8\xc3\xac\xc3\xb2\xc3\xb9'
>>> print 'àèìòù'.replace('\xa8', '')
à?ìòù
What before was valid UTF-8, isn't anymore. Using a unicode string you cannot operate in such a way that the resulting string isn't valid unicode text. You can remove a code point, replace a code point with a different code point etc. but you cannot mess with the internal representation.
The suggested technique above in Dave's answer is certainly a good design practice, and yes ultimately the required permission must be set in the AndroidManifest.xml file to access the external storage.
However, the Mono-esque way to add most (if not all, not sure) "manifest options" is through the attributes of the class implementing the activity (or service).
The Visual Studio Mono plugin automatically generates the manifest, so its best not to manually tamper with it (I'm sure there are cases where there is no other option).
For example:
[Activity(Label="MonoDroid App", MainLauncher=true, Permission="android.permission.WRITE_EXTERNAL_STORAGE")]
public class MonoActivity : Activity
{
protected override void OnCreate(Bundle bindle)
{
base.OnCreate(bindle);
}
}
Just a little addition to the answer of @dAm2k :
In addition to sudo apt-get remove --purge mysql\*
I've done a sudo apt-get remove --purge mariadb\*
.
I seems that in the new release of debian (stretch), when you install mysql it install mariadb package with it.
Hope it helps.
thanks to the answers of Steve Park and Rafal Borowiec I got my code working, however, I had one issue: the DriverManagerDataSource is a "simple" implementation and does NOT give you a ConnectionPool (check http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/datasource/DriverManagerDataSource.html).
Hence, I replaced the functions which returns the DataSource
for the secondDB
to.
public DataSource <secondaryDB>DataSource() {
// use DataSourceBuilder and NOT DriverManagerDataSource
// as this would NOT give you ConnectionPool
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.url(databaseUrl);
dataSourceBuilder.username(username);
dataSourceBuilder.password(password);
dataSourceBuilder.driverClassName(driverClassName);
return dataSourceBuilder.build();
}
Also, if do you not need the EntityManager
as such, you can remove both the entityManager()
and the @Bean
annotation.
Plus, you may want to remove the basePackages annotation of your configuration class: maintaining it with the factoryBean.setPackagesToScan()
call is sufficient.
This question was asked many years ago. Now, there is a better solution: SmartSwipe: https://github.com/luckybilly/SmartSwipe
code looks like this:
SmartSwipe.wrap(contentView)
.addConsumer(new StayConsumer()) //contentView stay while swiping with StayConsumer
.enableAllDirections() //enable directions as needed
.addListener(new SimpleSwipeListener() {
@Override
public void onSwipeOpened(SmartSwipeWrapper wrapper, SwipeConsumer consumer, int direction) {
//direction:
// 1: left
// 2: right
// 4: top
// 8: bottom
}
})
;
Also I tried other solution, but some of the code executed after redirect.
public static void ResponseRedirect(HttpResponse iResponse, string iUrl)
{
ResponseRedirect(iResponse, iUrl, HttpContext.Current);
}
public static void ResponseRedirect(HttpResponse iResponse, string iUrl, HttpContext iContext)
{
iResponse.Redirect(iUrl, false);
iContext.ApplicationInstance.CompleteRequest();
iResponse.BufferOutput = true;
iResponse.Flush();
iResponse.Close();
}
So if need to prevent code execution after redirect
try
{
//other code
Response.Redirect("")
// code not to be executed
}
catch(ThreadAbortException){}//do there id nothing here
catch(Exception ex)
{
//Logging
}
I think it is better to copy files from your local computer, because if files number or file size is very big, copying process could be interrupted if your current ssh session would be lost (broken pipe or whatever).
If you have configured ssh key to connect to your remote server, you could use the following command:
rsync -avP -e "ssh -i /home/local_user/ssh/key_to_access_remote_server.pem" remote_user@remote_host.ip:/home/remote_user/file.gz /home/local_user/Downloads/
Where v
option is --verbose
, a
option is --archive
- archive mode, P
option same as --partial
- keep partially transferred files, e
option is --rsh=COMMAND
- specifying the remote shell to use.
Depending of the editor that you're using there are some shortcuts to comment a block of lines.
Another workaround would be to put your code in an "if (0)" conditional block ;)
You could try implemeting something like this: http://www.codeproject.com/KB/cs/reporting__windowsforms.aspx
Firstly, you should clarify whether you mean:
The reason the distinction is necessary is that a label can technically include any characters, including the NUL, @
and '.
' characters. DNS is 8-bit capable and it's perfectly possible to have a zone file containing an entry reading "an\0odd\.l@bel
". It's not recommended of course, not least because people would have difficulty telling a dot inside a label from those separating labels, but it is legal.
However, URLs require a host name in them, and those are governed by RFCs 952 and 1123. Valid host names are a subset of domain names. Specifically only letters, digits and hyphen are allowed. Furthermore the first and last characters cannot be a hyphen. RFC 952 didn't permit a number for the first character, but RFC 1123 subsequently relaxed that.
Hence:
a
- valid0
- valida-
- invalida-b
- validxn--dasdkhfsd
- valid (punycode encoding of an IDN)Off the top of my head I don't think it's possible to invalidate the a-
example with a single simple regexp. The best I can come up with to check a single host label is:
if (preg_match('/^[a-z\d][a-z\d-]{0,62}$/i', $label) &&
!preg_match('/-$/', $label))
{
# label is legal within a hostname
}
To further complicate matters, some domain name entries (typically SRV
records) use labels prefixed with an underscore, e.g. _sip._udp.example.com
. These are not host names, but are legal domain names.
Try to rebase your local master branch onto your remote/origin master branch and resolve any conflicts in the process.
Use this for windows Server 2008 r2 and Windows Server 2012 R2
Click Start, click Run, type dcomcnfg and then click OK to open Component Services.
In the console tree, click to expand Component Services, click to expand Computers, click to expand My Computer, click to expand Distributed Transaction Coordinator and then click Local DTC.
Right click Local DTC and click Properties to display the Local DTC Properties dialog box.
Click the Security tab.
Check mark "Network DTC Access" checkbox.
Finally check mark "Allow Inbound" and "Allow Outbound" checkboxes.
Click Apply, OK.
A message will pop up about restarting the service.
Click OK and That's all.
Reference : https://msdn.microsoft.com/en-us/library/dd327979.aspx
Note: Sometimes the network firewall on the Local Computer or the Server could interrupt your connection so make sure you create rules to "Allow Inbound" and "Allow Outbound" connection for C:\Windows\System32\msdtc.exe
This issue happened when I accidently renamed the line
apply plugin: 'com.android.application'
on file app/build.gradle
to some other name. So, I fixed it by changing it to what it was.
It depends on how correct you want to be. \n
will usually do the job. If you really want to get it right, you look up the newline character in the os
package. (It's actually called linesep
.)
Note: when writing to files using the Python API, do not use the os.linesep
. Just use \n
; Python automatically translates that to the proper newline character for your platform.