Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("in.txt")
Dim inFile: Set inFile = obj.OpenTextFile("out.txt")
' Read file
Dim strRetVal : strRetVal = inFile.ReadAll
inFile.Close
' Write file
outFile.write (strRetVal)
outFile.Close
I'd recommend using get_included_files
- as Pascal says you're either looking at the wrong file somehow or this function is already defined in a file that's been included.
require_once
is also useful if the file you're attempting to include is essential.
I know this post is super old, but it is still coming up as the top hit in google so I will add some more info to this issue.
I was having the same problems as OP but none of the suggested answers seemed to work for me. Mainly because "config-win.h" didn't exist anywhere in the connector install folder.
I was using the latest Connector C 6.1.6 as that was what was suggested by the MySQL installer.
This however doesn't seem to be supported by the latest MySQL-python package (1.2.5). When trying to install it I could see that it was explicitly looking for C Connector 6.0.2.
"-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include"
So by installing this version from https://dev.mysql.com/downloads/file/?id=378015 the python package installed without any problem.
In my Ubuntu, I have a headache for 2 days on this issue.
Step 1. Type on the terminal whereis java
then it will display something like this
java: /usr/bin/java /etc/java /usr/share/java /usr/lib/jvm/java-8-openjdk-amd64/bin/java /usr/share/man/man1/java.1.gz
Step 2. Take note of the path:
/usr/lib/jvm/java-8-openjdk-amd64/bin/java
exclude the bin/java
your JAVA_HOME = /usr/lib/jvm/java-8-openjdk-amd64
This may be useful:
var serializer = new JavaScriptSerializer();
dynamic jsonObject = serializer.Deserialize<dynamic>(json);
Where "json" is the string that contains the JSON values. Then to retrieve the values from the jsonObject you may use
myProperty = Convert.MyPropertyType(jsonObject["myProperty"]);
Changing MyPropertyType to the proper type (ToInt32, ToString, ToBoolean, etc).
Check if you have something configured inside the config file /application/config/config.php
e.g.
$config['base_url'] = 'http://example.com/';
Feb 3rd 2020:
---
did produce the line, but I could not get new lines to work with suggestions above.[space][space]
suggestion, since my editor removes trailing spaces on save, and I like this feature on.I ended up doing this:
TEXT...
<br><hr><br>
TEXT...
Resulting in:
TEXT...
<AN EMPTY LINE>
----------------- AN HORIZONTAL LINE ----------------
<AN EMPTY LINE>
TEXT...
I just added an @ symbol and it started working. Like this: @$product->save();
I do think mapping the Content-Type header in the request will also work. This will work even for cases when you upload a file with no extension. (when filename does not have an extension in the request)
Assume you are sending your data using HTTP POST:
POST /upload2 HTTP/1.1
Host: localhost:7098
Connection: keep-alive
Content-Length: 1047799
Accept: */*
Origin: http://localhost:63342
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36
Content-Type: multipart/form-data; boundary=---- WebKitFormBoundaryPDULZN8DYK3VppPp
Referer: http://localhost:63342/Admin/index.html? _ijt=3a6a054pasorvrljf8t8ea0j4h
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,az;q=0.6,tr;q=0.4
Request Payload
------WebKitFormBoundaryPDULZN8DYK3VppPp
Content-Disposition: form-data; name="image"; filename="blob"
Content-Type: image/png
------WebKitFormBoundaryPDULZN8DYK3VppPp--
Here name Content-Type header contains the mime type of the data. Mapping this mime type to an extension will get you the file extension :).
Restify BodyParser converts this header in to a property with name type
File {
domain:
Domain {
domain: null,
_events: { .... },
_eventsCount: 1,
_maxListeners: undefined,
members: [ ... ] },
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
size: 1047621,
path: '/tmp/upload_2a4ac9ef22f7156180d369162ef08cb8',
name: 'blob',
**type: 'image/png'**,
hash: null,
lastModifiedDate: Wed Jul 20 2016 16:12:21 GMT+0300 (EEST),
_writeStream:
WriteStream {
... },
writable: true,
domain:
Domain {
...
},
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
path: '/tmp/upload_2a4ac9ef22f7156180d369162ef08cb8',
fd: null,
flags: 'w',
mode: 438,
start: undefined,
pos: undefined,
bytesWritten: 1047621,
closed: true }
}
You can use this header and do the extension mapping (substring etc ...) manually, but there are also ready made libraries for this. Below two were the top results when i did a google search
and their usage is simple as well:
app.post('/upload2', function (req, res) {
console.log(mime.extension(req.files.image.type));
}
above snippet will print png to console.
I think I usually used eqnarray or something. It lets you say
\begin{eqnarray*}
x &=& blah blah blah \\
& & more blah blah blah \\
& & even more blah blah
\end{eqnarray*}
and it will be aligned by the & &... As pkaeding mentioned, it's hard to read, but when you've got an equation thats that long, it's gonna be hard to read no matter what... (The * makes it not have an equation number, IIRC)
Here is a table of the different events and the levels of browser support. You need to pick an event which is supported across at least all modern browsers.
As you will see from the table, the keypress
and change
event do not have uniform support whereas the keyup
event does.
Also make sure you attach the event handler using a cross-browser-compatible method...
For (PHP >= 5.2.0):
You can use DateTime class. However you might need to change your date format. Didn't try yours.
The following date format will work for sure: YYYY-MM-DD HH-MM-SS
$date = new DateTime("2010-04-08 22:15:00");
echo $date->format("g"). '.' .$date->format("i"). ' ' .$date->format("A");
//output
//10.15 PM
However, in my opinion, using .
as a separator for 10.15
is not recommended because your users might be confused either this is a decimal number or time format. The most common way is to use 10:15 PM
I didn't want to introduce an asset catalog.
Per the answer from seahorseseaeo here, adding the following to info.plist worked for me. (I edited it as a "source code".) I then named the images [email protected] and [email protected]
<key>UILaunchImages</key>
<array>
<dict>
<key>UILaunchImageMinimumOSVersion</key>
<string>8.0</string>
<key>UILaunchImageName</key>
<string>Default-667h</string>
<key>UILaunchImageOrientation</key>
<string>Portrait</string>
<key>UILaunchImageSize</key>
<string>{375, 667}</string>
</dict>
<dict>
<key>UILaunchImageMinimumOSVersion</key>
<string>8.0</string>
<key>UILaunchImageName</key>
<string>Default-736h</string>
<key>UILaunchImageOrientation</key>
<string>Portrait</string>
<key>UILaunchImageSize</key>
<string>{414, 736}</string>
</dict>
</array>
I had the same problem in windows The error was that I had installed several versions of PHP and the Environment Variables were routing to wrong Path of php see image example
When you specify position:absolute it positions itself to the next-highest element with position:relative. In this case, that's the .project div.
If you give the image's immediate parent div a style of position:relative, the overlay will key to that instead of the div which includes the text. For example: http://jsfiddle.net/7gYUU/1/
<div class="parent">
<img src="http://placehold.it/500x500" class="img-responsive"/>
<div class="fa fa-plus project-overlay"></div>
</div>
.parent {
position: relative;
}
In Rails 4.1.0, I have faced problem with saving latitude and longitude to MySql database. It can't save large fraction number with float data type. And I change the data type to decimal and working for me.
def change change_column :cities, :latitude, :decimal, :precision => 15, :scale => 13 change_column :cities, :longitude, :decimal, :precision => 15, :scale => 13 end
var currentTallest = 0,_x000D_
currentRowStart = 0,_x000D_
rowDivs = new Array(),_x000D_
$el,_x000D_
topPosition = 0;_x000D_
_x000D_
$('.blocks').each(function() {_x000D_
_x000D_
$el = $(this);_x000D_
topPostion = $el.position().top;_x000D_
_x000D_
if (currentRowStart != topPostion) {_x000D_
_x000D_
// we just came to a new row. Set all the heights on the completed row_x000D_
for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {_x000D_
rowDivs[currentDiv].height(currentTallest);_x000D_
}_x000D_
_x000D_
// set the variables for the new row_x000D_
rowDivs.length = 0; // empty the array_x000D_
currentRowStart = topPostion;_x000D_
currentTallest = $el.height();_x000D_
rowDivs.push($el);_x000D_
_x000D_
} else {_x000D_
_x000D_
// another div on the current row. Add it to the list and check if it's taller_x000D_
rowDivs.push($el);_x000D_
currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);_x000D_
_x000D_
}_x000D_
_x000D_
// do the last row_x000D_
for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {_x000D_
rowDivs[currentDiv].height(currentTallest);_x000D_
}_x000D_
_x000D_
});?
_x000D_
$('.blocks') would be changed to use whatever CSS selector you need to equalize.
_x000D_
If you can't go over your time limit (it's a hard limit) then a thread is your best bet. You can use a loop to terminate the thread once you get to the time threshold. Whatever is going on in that thread at the time can be interrupted, allowing calculations to stop almost instantly. Here is an example:
Thread t = new Thread(myRunnable); // myRunnable does your calculations
long startTime = System.currentTimeMillis();
long endTime = startTime + 60000L;
t.start(); // Kick off calculations
while (System.currentTimeMillis() < endTime) {
// Still within time theshold, wait a little longer
try {
Thread.sleep(500L); // Sleep 1/2 second
} catch (InterruptedException e) {
// Someone woke us up during sleep, that's OK
}
}
t.interrupt(); // Tell the thread to stop
t.join(); // Wait for the thread to cleanup and finish
That will give you resolution to about 1/2 second. By polling more often in the while loop, you can get that down.
Your runnable's run would look something like this:
public void run() {
while (true) {
try {
// Long running work
calculateMassOfUniverse();
} catch (InterruptedException e) {
// We were signaled, clean things up
cleanupStuff();
break; // Leave the loop, thread will exit
}
}
Update based on Dmitri's answer
Dmitri pointed out TimerTask, which would let you avoid the loop. You could just do the join call and the TimerTask you setup would take care of interrupting the thread. This would let you get more exact resolution without having to poll in a loop.
I needed to do a count of a very complex query with many joins. I was using the joins as filters, so I only wanted to know the count of the actual objects. count() was insufficient, but I found the answer in the docs here:
http://docs.sqlalchemy.org/en/latest/orm/tutorial.html
The code would look something like this (to count user objects):
from sqlalchemy import func
session.query(func.count(User.id)).scalar()
If useful, try this:
BufferedImage imgBuffer = ImageIO.read(new File("c:\\image.bmp"));
byte[] pixels = (byte[])imgBuffer.getRaster().getDataElements(0, 0, imgBuffer.getWidth(), imgBuffer.getHeight(), null);
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
You can also use remove to remove a value by index as well.
n = [1, 3, 5]
n.remove(n[1])
n would then refer to [1, 5]
For swift 3, I couldn't use just reachability from RAJAMOHAN-S solutions since it returns "true" if there is WiFi but no Internet. Thus, I implemented second validation via URLSession class and completion handler.
Here is the whole class.
import Foundation
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
// Working for Cellular and WIFI
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
let ret = (isReachable && !needsConnection)
return ret
}
class func isInternetAvailable(webSiteToPing: String?, completionHandler: @escaping (Bool) -> Void) {
// 1. Check the WiFi Connection
guard isConnectedToNetwork() else {
completionHandler(false)
return
}
// 2. Check the Internet Connection
var webAddress = "https://www.google.com" // Default Web Site
if let _ = webSiteToPing {
webAddress = webSiteToPing!
}
guard let url = URL(string: webAddress) else {
completionHandler(false)
print("could not create url from: \(webAddress)")
return
}
let urlRequest = URLRequest(url: url)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
if error != nil || response == nil {
completionHandler(false)
} else {
completionHandler(true)
}
})
task.resume()
}
}
And you call this like this, for example:
Reachability.isInternetAvailable(webSiteToPing: nil) { (isInternetAvailable) in
guard isInternetAvailable else {
// Inform user for example
return
}
// Do some action if there is Internet
}
AFAIK JSON.Net does not provide functionality for reading from a URL. So you need to do this in two steps:
using (var webClient = new System.Net.WebClient()) {
var json = webClient.DownloadString(URL);
// Now parse with JSON.Net
}
You can use this google service free IP geolocation webservice
update
the link is broken, I put here other link that include @NickSweeting in the comments:
and you can get the data in json format:
The other answers cover what it is quite well. I'm not repeating that. Just some points that might be useful to you.
Usually, memoisation is an operation you can apply on any function that computes something (expensive) and returns a value. Because of this, it's often implemented as a decorator. The implementation is straightforward and it would be something like this
memoised_function = memoise(actual_function)
or expressed as a decorator
@memoise
def actual_function(arg1, arg2):
#body
For any newcomers, as of April 2015, Android now has a SortedList class in the support library, designed specifically to work with RecyclerView
. Here's the blog post about it.
mikej's answer was very precise and helpful, but the the thing i also wanted to know was how to get current method name in rails.
found out it's possible with self.current_method
easily found at http://www.ruby-forum.com/topic/75258
No one seems to have included the which function. It can also prove useful for filtering.
expr[which(expr$cell == 'hesc'),]
This will also handle NAs and drop them from the resulting dataframe.
Running this on a 9840 by 24 dataframe 50000 times, it seems like the which method has a 60% faster run time than the %in% method.
You need to escape the double-quotes inside the search string, like this:
string orig = "\"Text\",\"Text\",\"Text\"";
string res = orig.Replace("\",\"", ";");
Note that the replacement does not occur "in place", because .NET strings are immutable. The original string will remain the same after the call; only the returned string res
will have the replacements.
I think this means that
You have three options to solve this
Use maven-compiler-plugin version or later, because
NOTE: Since 3.8.0 the default value has changed from 1.5 to 1.6 See https://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html#target
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
Indicate to the maven-compiler-plugin to use source level 6 and target 6 (or later).
Best practice recommended by https://maven.apache.org/plugins/maven-compiler-plugin/
Also note that at present the default source setting is 1.6 and the default target setting is 1.6, independently of the JDK you run Maven with. You are highly encouraged to change these defaults by setting source and target as described in Setting the -source and -target of the Java Compiler.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
or use
<properties>
<maven.compiler.source>1.6</maven.compiler.source>
<maven.compiler.target>1.6</maven.compiler.target>
</properties>
And a key point - although TRUNCATE TABLE seems like a DELETE with no WHERE clause, TRUNCATE is not DML, it is DDL. DELETE requires a COMMIT, but TRUNCATE does not.
Many of the suggestions unfortunately do not work for all Markdown viewers/editors, for instance, the popular Markdown Viewer Chrome extension, but they do work with iA Writer.
What does seem to work across both of these popular programs (and might work for your particular application) is to use HTML comment blocks ('<!-- -->')
:
| <!-- --> | <!-- --> |
|-------------|-------------|
| Foo | Bar |
Like some of the earlier suggestions stated, this does add an empty header row in your Markdown viewer/editor. In iA Writer, it's aesthetically small enough that it doesn't get in my way too much.
NSDictionary -> NSData:
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:yourDictionary forKey:@"Some Key Value"];
[archiver finishEncoding];
[archiver release];
// Here, data holds the serialized version of your dictionary
// do what you need to do with it before you:
[data release];
NSData -> NSDictionary
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSDictionary *myDictionary = [[unarchiver decodeObjectForKey:@"Some Key Value"] retain];
[unarchiver finishDecoding];
[unarchiver release];
[data release];
You can do that with any class that conforms to NSCoding.
Beside accepted answer, you need to hold a reference of listener and remove when you don't need it. Otherwise you will get a null pointer exception for your ScrollView and memory leak (mentioned in comments of accepted answer).
You can implement OnScrollChangedListener in your activity/fragment.
MyFragment : ViewTreeObserver.OnScrollChangedListener
Add it to scrollView when your view is ready.
scrollView.viewTreeObserver.addOnScrollChangedListener(this)
Remove listener when no longer need (ie. onPause())
scrollView.viewTreeObserver.removeOnScrollChangedListener(this)
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-4">
<a href="">About</a>
</div>
<div class="col-md-4">
<img src="image.png">
</div>
<div class="col-md-4">
<a href="#myModal1" data-toggle="modal">SHARE</a>
</div>
</div>
</div>
</div>
</div>
You need to nest the interior columns inside of a row rather than just another column. It offsets the padding caused by the column with negative margins.
A simpler way would be
<div class="container">
<div class="row">
<div class="col-md-4">
<a href="">About</a>
</div>
<div class="col-md-4">
<img src="image.png">
</div>
<div class="col-md-4">
<a href="#myModal1" data-toggle="modal">SHARE</a>
</div>
</div>
</div>
The following piece of code works for me:
string image_path="physical path of your image";
byte[] byes_array = System.IO.File.ReadAllBytes(Server.MapPath(image_path));
string base64String = Convert.ToBase64String(byes_array);
As the error message says in the last line: the module models
in the file c:\projects\mysite..\mysite\polls\models.py
contains no class model
. This error occurs in the definition of the Poll
class:
class Poll(models.model):
Either the class model
is misspelled in the definition of the class Poll
or it is misspelled in the module models
. Another possibility is that it is completely missing from the module models
. Maybe it is in another module or it is not yet implemented in models
.
JAVA Fax Api documentation
You could download the mac 2.2 preview release from here and unzip it.
http://www.oracle.com/technetwork/java/javafx/downloads/devpreview-1429449.html
The javadoc won't quite match 2.1, but it will be close and if you use the preview instead, it will match exactly.
I think this would help you :)
See http://www.oracle.com/technetwork/java/faq-137059.html
JSP technology is part of the Java technology family. JSP pages are compiled into servlets and may call JavaBeans components (beans) or Enterprise JavaBeans components (enterprise beans) to perform processing on the server. As such, JSP technology is a key component in a highly scalable architecture for web-based applications.
See https://jcp.org/en/introduction/faq
A: JavaServer Faces technology is a framework for building user interfaces for web applications. JavaServer Faces technology includes:
A set of APIs for: representing UI components and managing their state, handling events and input validation, defining page navigation, and supporting internationalization and accessibility.
A JavaServer Pages (JSP) custom tag library for expressing a JavaServer Faces interface within a JSP page.
JSP is a specialized kind of servlet.
JSF is a set of tags you can use with JSP.
I found out the answer is probably:
A NativeQuery lets you execute native SQL, mapping the results according to your specifications. Such a specification that describes how an SQL result set is mapped to a Doctrine result is represented by a ResultSetMapping.
Source: Native SQL.
This is an example using the Expr() Class - I needed this too some days ago and it took me some time to find out what is the exact syntax and way of usage:
/**
* fetches Products that are more expansive than the given price
*
* @param int $price
* @return array
*/
public function findProductsExpensiveThan($price)
{
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder();
$q = $qb->select(array('p'))
->from('YourProductBundle:Product', 'p')
->where(
$qb->expr()->gt('p.price', $price)
)
->orderBy('p.price', 'DESC')
->getQuery();
return $q->getResult();
}
It's a choice (from browser devs or W3C, I can't find any W3C specification about styling select options though) not allowing to style select options.
I suspect this would be to keep consistency with native choice lists.
(think about mobile devices for example).
3 solutions come to my mind:
ul
s (allowing many things)select
s into multiple in order to group valuesoptgroup
CTRL+SHIFT+ENTER, ARRAY FORMULA EXCEL 2016 MAC. So I arrive late into the game, but maybe someone else will. This almost drove me nuts. No matter what I searched for in Google I came up empty. Whatever I tried, no solution seemed to be in sight. Switched to Excel 2016 quite some time ago and today I needed to do some array formulas. Also sitting on a MacBook Pro 15 Touch Bar 2016. Not that it really matters, but still, since the solution was published on Youtube in 2013. The reason why, for me anyway, nothing worked, is in the Mac OS, the control key by default, for me anyway, is set to manage Mission control, which, at least for me, disabled the control button in Excel. In order to enable the key to actually control functions in Excel, you need to go to System preferences > Mission Control, and disable shortcuts for Mission control. So, let's see how long this solution will last. Probably be back to square one after the coffee break. Have a good one!
The newer iCalendar format, with more data attached, includes information about the person who created the event, so that when it is imported into Outlook (for example), changes to that event are communicated via email to the creator. This can be helpful when you need to inform others of any changes.
However, when I am just exporting an event from one of my calendars to another, I prefer to use vCalendar, since this does not require sending an email message to the creator (usually myself) if I make a change or delete something.
Enums are real objects that exist at runtime. So you are able to reverse the mapping doing something like this:
let value = GoalProgressMeasurements.Not_Measured;
console.log(GoalProgressMeasurements[value]);
// => Not_Measured
Based on that you can use the following code:
export enum GoalProgressMeasurements {
Percentage = 1,
Numeric_Target = 2,
Completed_Tasks = 3,
Average_Milestone_Progress = 4,
Not_Measured = 5
}
let map: {id: number; name: string}[] = [];
for(var n in GoalProgressMeasurements) {
if (typeof GoalProgressMeasurements[n] === 'number') {
map.push({id: <any>GoalProgressMeasurements[n], name: n});
}
}
console.log(map);
Reference: https://www.typescriptlang.org/docs/handbook/enums.html
You can try/catch PDOException
s (your configs could differ but the important part is the try/catch):
try {
$dbh = new PDO(
DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
DB_USER,
DB_PASS,
[
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . DB_CHARSET . ' COLLATE ' . DB_COLLATE
]
);
} catch ( PDOException $e ) {
echo 'ERROR!';
print_r( $e );
}
The print_r( $e );
line will show you everything you need, for example I had a recent case where the error message was like unknown database 'my_db'
.
GROUP BY can be selected from Total row in query design view in MS Access.
If Total row not shown in design view (as in my case). You can go to SQL View and add GROUP By fname etc. Then Total row will automatically show in design view.
You have to select as Expression in this row for calculated fields.
The NSURLErrorDomain
error codes are listed here https://developer.apple.com/documentation/foundation/1508628-url_loading_system_error_codes
However, 400 is just the http status code (http://www.w3.org/Protocols/HTTP/HTRESP.html) being returned which means you've got something wrong with your request.
To get list of all keys
using System.Linq;
List<String> myKeys = myDict.Keys.ToList();
System.Linq is supported in .Net framework 3.5 or above. See the below links if you face any issue in using System.Linq
Try to use this :
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < chBoxListTables.Items.Count; i++)
if (chBoxListTables.GetItemCheckState(i) == CheckState.Checked)
{
txtBx.text += chBoxListTables.Items[i].ToString() + " \n";
}
}
use display:inline-block;
instead of float
you can't centre floats, but inline-blocks centre as if they were text, so on the outer overall container of your "row" - you would set text-align: center;
then for each image/caption container (it's those which would be inline-block;
) you can re-align the text to left if you require
While making image with fully transparent background in PNG-8, the outline of the image looks prominent with little white bits. But in PNG-24 the outline is gone and looks perfect. Transparency in PNG-24 is greater and cleaner than PNG-8.
PNG-8 contains 256 colors, while PNG-24 contains 16 million colors.
File size is almost double in PNG-24 than PNG-8.
Well, your addActiveClass needs to know what was clicked. Something like this could work (notice that I've added the information which divs are active as a state array, and that onClick now passes the information what was clicked as a parameter after which the state is accordingly updated - there are certainly smarter ways to do it, but you get the idea).
class Test extends Component(){
constructor(props) {
super(props);
this.state = {activeClasses: [false, false, false]};
this.addActiveClass= this.addActiveClass.bind(this);
}
addActiveClass(index) {
const activeClasses = [...this.state.activeClasses.slice(0, index), !this.state.activeClasses[index], this.state.activeClasses.slice(index + 1)].flat();
this.setState({activeClasses});
}
render() {
const activeClasses = this.state.activeClasses.slice();
return (
<div>
<div className={activeClasses[0]? "active" : "inactive"} onClick={() => this.addActiveClass(0)}>
<p>0</p>
</div>
<div className={activeClasses[1]? "active" : "inactive"} onClick={() => this.addActiveClass(1)}>
<p>1</p>
</div>
<div onClick={() => this.addActiveClass(2)}>
<p>2</p>
</div>
</div>
);
}
}
Attempt to provide simplified explanation:
SAP
Now, that SAP has created an environment around SAP. In order to operate in SAP environment (i.e. for customisations etc.), language-abstraction was required. Here comes ABAP.
ABAP
Therefore, any customisation on the basic version of SAP given to some customer of SAP would require ABAP usage, otherwise, just delivered SAP is good enough for usage (i.e. no ABAP required).
Now is another term HANA.
HANA
SAP and HANA together abstracts the underlying complexity of database-access queries and UI (developed in java), together, to make the user experience good for the management system (used majorly in analytics, and so that the main focus stays in analytics). This very specific tool/product, is said as "technology", as it has an environment of its own (terminologies etc.). ABAP facilitates further development of the SAP-ERP.
The underlying development is in C, C++ (and ABAP) for SAP.
public Node reverseListRecursive(Node curr)
{
if(curr == null){//Base case
return head;
}
else{
(reverseListRecursive(curr.next)).next = (curr);
}
return curr;
}
Also be sure that your file is actually a CSV file. For example, if you had an .xls file, and simply changed the file extension to .csv, the file won't import and will give the error above. To check to see if this is your problem open the file in excel and it will likely say:
"The file format and extension of 'Filename.csv' don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?"
To fix the file: open the file in Excel, click "Save As", Choose the file format to save as (use .cvs), then replace the existing file.
This was my problem, and fixed the error for me.
a = [5, 1, 6, 14, 2, 8]
b = [2, 6, 15]
a - b
# => [5, 1, 14, 8]
b - a
# => [15]
(b - a).empty?
# => false
Open SDK Manager and download Intel x86 Emulator Accelerator (HAXM installer) if you haven't.
Now go to your SDK directory (C:\users\username\AppData\Local\Android\sdk, generally). In this directory, go to extras ? Intel ? Hardware_Accelerated_Execution_Manager and run the file named "intelhaxm-android.exe".
In case you get an error like "Intel virtualization technology (vt,vt-x) is not enabled", go to your BIOS settings and enable hardware virtualization.
Restart Android Studio and then try to start the AVD again.
It might take a minute or 2 to show the emulator window.
swift 5 and above
case 1 : using with Navigation controller
self.navigationController?.popViewController(animated: true)
case 2 : using with present view controller
self.dismiss(animated: true, completion: nil)
try
<div style='overflow:auto; width:400px;height:400px;'>here is some text</div>
You should assume the socket was closed on the other end. Wrap your code with a try catch block for IOException.
You can use isConnected() to determine if the SocketChannel is connected or not, but that might change before your write() invocation finishes. Try calling it in your catch block to see if in fact this is why you are getting the IOException.
At least for MS VC++, the C Runtime library has several functions that I've found helpful in the past. Check the MSDN help for the _Crt*
functions.
Here's a simple example of how to load JSON data into an Angular model.
I have a JSON 'GET' web service which returns a list of Customer details, from an online copy of Microsoft's Northwind SQL Server database.
http://www.iNorthwind.com/Service1.svc/getAllCustomers
It returns some JSON data which looks like this:
{
"GetAllCustomersResult" :
[
{
"CompanyName": "Alfreds Futterkiste",
"CustomerID": "ALFKI"
},
{
"CompanyName": "Ana Trujillo Emparedados y helados",
"CustomerID": "ANATR"
},
{
"CompanyName": "Antonio Moreno Taquería",
"CustomerID": "ANTON"
}
]
}
..and I want to populate a drop down list with this data, to look like this...
I want the text of each item to come from the "CompanyName" field, and the ID to come from the "CustomerID" fields.
How would I do it ?
My Angular controller would look like this:
function MikesAngularController($scope, $http) {
$scope.listOfCustomers = null;
$http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
.success(function (data) {
$scope.listOfCustomers = data.GetAllCustomersResult;
})
.error(function (data, status, headers, config) {
// Do some error handling here
});
}
... which fills a "listOfCustomers" variable with this set of JSON data.
Then, in my HTML page, I'd use this:
<div ng-controller='MikesAngularController'>
<span>Please select a customer:</span>
<select ng-model="selectedCustomer" ng-options="customer.CustomerID as customer.CompanyName for customer in listOfCustomers" style="width:350px;"></select>
</div>
And that's it. We can now see a list of our JSON data on a web page, ready to be used.
The key to this is in the "ng-options" tag:
customer.CustomerID as customer.CompanyName for customer in listOfCustomers
It's a strange syntax to get your head around !
When the user selects an item in this list, the "$scope.selectedCustomer" variable will be set to the ID (the CustomerID field) of that Customer record.
The full script for this example can be found here:
Mike
I can't seem to make this work with the latest mysql or mysql:5.7. So I use mariaDB instead. Here is my docker-compose.yaml
code.
version: '3'
services:
mysql:
image: mariadb:10.3
container_name: mariadb
volumes:
- container-volume:/var/lib/mysql
- ./dump.sql:/docker-entrypoint-initdb.d/dump.sql
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: name_db
ports:
- "3306:3306"
volumes:
container-volume:
Use a image style width and height 100% . This will do the trick, because the image can be resized based on the container.
Example:
<a class="navbar-brand" href="#" style="padding: 4px;margin:auto"> <img src="images/logo.png" style="height:100%;width: auto;" title="mycompanylogo"></a>
git rm --cached
will remove it from the commit set ("un-adding" it); that sounds like what you want.
You can check your numbers by checking their constructor.
var i = "5";
if( i.constructor !== Number )
{
console.log('This is not number'));
}
Declare the array size will solve your problem
String[] title = {
"Abundance",
"Anxiety",
"Bruxism",
"Discipline",
"Drug Addiction"
};
String urlbase = "http://www.somewhere.com/data/";
String imgSel = "/logo.png";
String[] mStrings = new String[title.length];
for(int i=0;i<title.length;i++) {
mStrings[i] = urlbase + title[i].toLowerCase() + imgSel;
System.out.println(mStrings[i]);
}
I followed the answers by @wize and @mdelolmo and I got the solution. Thanks Tons. But, I tuned these solutions a little bit to improve the memory consumption.
Problems I observed:
They save the instance of Fragment
which is replaced. In my case, it is a Fragment which holds MapView
and I thought its costly. So, I am maintaining the FragmentPagerPositionChanged (POSITION_NONE or POSITION_UNCHANGED)
instead of Fragment
itself.
Here is my implementation.
public static class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
private SwitchFragListener mSwitchFragListener;
private Switch mToggle;
private int pagerAdapterPosChanged = POSITION_UNCHANGED;
private static final int TOGGLE_ENABLE_POS = 2;
public DemoCollectionPagerAdapter(FragmentManager fm, Switch toggle) {
super(fm);
mToggle = toggle;
mSwitchFragListener = new SwitchFragListener();
mToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mSwitchFragListener.onSwitchToNextFragment();
}
});
}
@Override
public Fragment getItem(int i) {
switch (i)
{
case TOGGLE_ENABLE_POS:
if(mToggle.isChecked())
{
return TabReplaceFragment.getInstance();
}else
{
return DemoTab2Fragment.getInstance(i);
}
default:
return DemoTabFragment.getInstance(i);
}
}
@Override
public int getCount() {
return 5;
}
@Override
public CharSequence getPageTitle(int position) {
return "Tab " + (position + 1);
}
@Override
public int getItemPosition(Object object) {
// This check make sures getItem() is called only for the required Fragment
if (object instanceof TabReplaceFragment
|| object instanceof DemoTab2Fragment)
return pagerAdapterPosChanged;
return POSITION_UNCHANGED;
}
/**
* Switch fragments Interface implementation
*/
private final class SwitchFragListener implements
SwitchFragInterface {
SwitchFragListener() {}
public void onSwitchToNextFragment() {
pagerAdapterPosChanged = POSITION_NONE;
notifyDataSetChanged();
}
}
/**
* Interface to switch frags
*/
private interface SwitchFragInterface{
void onSwitchToNextFragment();
}
}
Demo link here.. https://youtu.be/l_62uhKkLyM
For demo purpose, used 2 fragments TabReplaceFragment
and DemoTab2Fragment
at position two. In all the other cases I'm using DemoTabFragment
instances.
Explanation:
I'm passing Switch
from Activity to the DemoCollectionPagerAdapter
. Based on the state of this switch we will display correct fragment. When the switch check is changed, I'm calling the SwitchFragListener
's onSwitchToNextFragment
method, where I'm changing the value of pagerAdapterPosChanged
variable to POSITION_NONE
. Check out more about POSITION_NONE. This will invalidate the getItem and I have logics to instantiate the right fragment over there. Sorry, if the explanation is a bit messy.
Once again big thanks to @wize and @mdelolmo for the original idea.
Hope this is helpful. :)
Let me know if this implementation has any flaws. That will be greatly helpful for my project.
Careful when running
export GOPATH=$HOME
Go assume that your code exists in specific places related to GOPATH
. So, instead, you can use docker to run any go command:
docker run -it -v $(pwd):/go/src/github.com/<organization name>/<repository name> golang
And now you can use any golang command, for example:
go test github.com/<organization name>/<repository name>
You can use Strings replace method with a regular expression.
"Hello World ".replace(/ /g, "");
The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp
/ / - Regular expression matching spaces
g - Global flag; find all matches rather than stopping after the first match
const str = "H e l l o World! ".replace(/ /g, "");_x000D_
document.getElementById("greeting").innerText = str;
_x000D_
<p id="greeting"><p>
_x000D_
I'm surprised not a lot of people know about the download attribute for a elements. Please help spread the word about it! You can have a hidden html link, and fake a click on it. If the html link has the download attribute it downloads the file, not views it, no matter what. Here's the code. It will download a cat picture if it can find it.
document.getElementById('download').click();
_x000D_
<a href="https://docs.google.com/uc?id=0B0jH18Lft7ypSmRjdWg1c082Y2M" download id="download" hidden></a>
_x000D_
Note: This is not supported on all browsers: http://www.w3schools.com/tags/att_a_download.asp
If you are using Resharper make sure it does not add the wrong header for you, very common cases with ReSharper are:
#include <consoleapi2.h
#include <apiquery2.h>
#include <fileapi.h>
UPDATE:
Another suggestion is to check if you are including a "partial Windows.h", what I mean is that if you include for example winbase.h or minwindef.h you may end up with that error, add "the big" Windows.h instead. There are also some less obvious cases that I went through, the most notable was when I only included synchapi.h, the docs clearly state that is the header to be included for some functions like AcquireSRWLockShared but it triggered the No target architecture, the fix was to remove the synchapi.h and include "the big" Windows.h.
The Windows.h is huge, it defines macros(many of them remove the No target arch error) and includes many other headers. In summary, always check if you are including some header that could be replaced by Windows.h because it is not unusual to include a header that relies on some constants that are defined by Windows.h, so if you fail to include this header your compilation may fail.
The redirect is one option. One thing you can try is to create a very simple index page that you place at the root of the WAR which does nothing else but redirecting to your controller like
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:redirect url="/welcome.html"/>
Then you map your controller with that URL with something like
@Controller("loginController")
@RequestMapping(value = "/welcome.html")
public class LoginController{
...
}
Finally, in web.xml, to have your (new) index JSP accessible, declare
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
If you want to preserve the order of the element with the same length as the original array, use bubble sort.
Input = ["ab","cdc","abcd","de"];
Output = ["ab","cd","cdc","abcd"]
Function:
function bubbleSort(strArray){
const arrayLength = Object.keys(strArray).length;
var swapp;
var newLen = arrayLength-1;
var sortedStrArrByLenght=strArray;
do {
swapp = false;
for (var i=0; i < newLen; i++)
{
if (sortedStrArrByLenght[i].length > sortedStrArrByLenght[i+1].length)
{
var temp = sortedStrArrByLenght[i];
sortedStrArrByLenght[i] = sortedStrArrByLenght[i+1];
sortedStrArrByLenght[i+1] = temp;
swapp = true;
}
}
newLen--;
} while (swap);
return sortedStrArrByLenght;
}
This is the proper way to access data in laravel :
@foreach($data-> ac as $link)
{{$link->url}}
@endforeach
I wrote a plugin called hasEventListener which exactly does that :
http://github.com/sebastien-p/jquery.hasEventListener
Hope this helps.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/tct_postpone_hour"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:gravity="center_vertical|center_horizontal"
android:text="1"
android:textSize="24dp" />
</RelativeLayout>
makes number one align in center both horizontal and vertical.
In order to find chart data using the financial data API of Google, one must simply go to Google as if looking for a search term, type finance into the search engine, and a link to Google finance will appear. Once at the Google finance search engine, type the ticker name into the financial data API engine and the result will be displayed. However, it should be noted that all Google finance charts are delayed by 15 minutes, and at most can be used for a better understanding of the ticker's past history, rather than current price.
A solution to the delayed chart information is to obtain a real-time financial data API. An example of one would be the barchartondemand interface that has real-time quote information, along with other detailed features that make it simpler to find the exact chart you're looking for. With fully customizable features, and specific programming tools for the precise trading information you need, barchartondemand's tools outdo Google finance by a wide margin.
There is already an ISO standard for this; no need to invent your own scheme:
http://en.wikipedia.org/wiki/ISO_5218
Per the standard, the column should be called "Sex" and the 'closest' data type would be tinyint with a CHECK constraint or lookup table as appropriate.
UPD 2020: "Open Graph Object Debugger" has been discontinued. Use Sharing Debugger to refresh Facebook cache.
There is some confusion about tons of Facebook Tools and Documentation. So many people probably use the Sharing Debugger tool to check their OpenGraph markup: https://developers.facebook.com/tools/debug/sharing/
But it only retrieves the information about your site from the Facebook cache. This means that after you change the ogp-markup on your site, the Sharing Debugger will still be using the old cached data. Moreover, if there is no cached data on the Facebook server then the Sharing Debugger will show you the error: This URL hasn't been shared on Facebook before.
So, the solution is to use another tool – Open Graph Object Debugger: https://developers.facebook.com/tools/debug/og/object/
It allows you to Fetch new scrape information and refresh the Facebook cache:
Honestly, I don't know how to find this tool exploring the Tools & Support section of developers.facebook.com – I cannot find any links and mentions. I only have this tool in my bookmarks. That's Facebook :)
I also noted that some developers use the name
attribute instead of property
. Many parsers probably will process such tags properly, but according to The Open Graph protocol, we should use property
, not name
:
<meta property="og:url" content="http://www.mywebaddress.com"/>
The last recommendation is to specify full URLs. For example, Facebook complains when you use relative URL in og:image
. So use the full one:
<meta property="og:image" content="http://www.mywebaddress.com/myimage.jpg"/>
I ran into the same issue in Ubuntu 18.04.3 LTS. In my case, apt installed gradle version 4.4.1. The already-install java version was 11.0.4
The build message I got was
Could not determine java version from '11.0.4'.
At the time, most of the online docs referenced gradle version 5.6, so I did the following:
sudo add-apt-repository ppa:cwchien/gradle
sudo apt update
sudo apt upgrade gradle
Then I repeated the project initialiation (using "gradle init" with the defaults). After that, "./gradlew build" worked correctly.
I later read a comment regarding a change in format of the output from "java --version" that caused gradle to break, which was fixed in a later version of gradle.
There seem to be something quirky with the 'automatic' entitlements in Xcode 4.6.
There is an Entitlement.plist file for each SDK at:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.1.sdk/Entitlements.plist
A workaround solution I came up with was to edit this file and add the sneaky aps-environment key manually like so:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>application-identifier</key>
<string>$(AppIdentifierPrefix)$(CFBundleIdentifier)</string>
<key>aps-environment</key>
<string>development</string>
<key>keychain-access-groups</key>
<array>
<string>$(AppIdentifierPrefix)$(CFBundleIdentifier)</string>
</array>
</dict>
</plist>
Then, Xcode is generating correct Xcent file, which contains the aps-environment key at:
/Users/mySelf/Library/Developer/Xcode/DerivedData/myApp-buauvgusocvjyjcwdtpewdzycfmc/Build/Intermediates/myApp.build/Debug-iphoneos/myApp.build/myApp.xcent
You can locate where your Xcent file is created using Xcode's Log Navigator,
look for "ProcessProductPackaging".
Unfortunately, this is the only way I found that fixes the issue.
(and finally able to properly get push token now)
Just wondering if another more elegant solution is available.
Please see my SO question for more details on that:
Xcode 4.6 automatic entitlement not working - "no valid aps-environment"
I don't think there's a 'simple' solution. You'll probably need to use both the events onKeyUp and onChange so that you also catch when changes are made with the mouse. Every time your code is called you can store the value you've 'seen' on this.seenValue attached right to the field. This should make a little easier.
VB.NET Sample Code
Dim A as String = "5.3"
Dim B as Double
B = CDbl(Val(A)) '// Val do hard work
'// Get output
MsgBox (B) '// Output is 5,3 Without Val result is 53.0
When there is no records returned from Database for a particular condition and When I tried to access the rs.getString(1); I got this error "exhausted resultset".
Before the issue, my code was:
rs.next();
sNr= rs.getString(1);
After the fix:
while (rs.next()) {
sNr = rs.getString(1);
}
Use reload for IE and set src for other browsers. (reload does not work on FF) tested on IE 7,8,9 and Firefox
if(navigator.appName == "Microsoft Internet Explorer"){
window.document.getElementById('iframeId').contentWindow.location.reload(true);
}else {
window.document.getElementById('iframeId').src = window.document.getElementById('iframeId').src;
}
Leaving an answer for anyone looking to do something similar but in a horizontal direction, like I wanted to.
Tweaking @strider820's answer like below will do the magic:
.fixed-content { //comments showing what I replaced.
left:0; //top: 0;
right:0; //bottom:0;
position:fixed;
overflow-y:hidden; //overflow-y:scroll;
overflow-x:auto; //overflow-x:hidden;
}
That's it. Also check this comment where @train explained using overflow:auto
over overflow:scroll
.
PHP allows "hinting" where you supply a class to specify an object. According to the PHP manual, "Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported." The error is confusing because of your choice of "string" - put "myClass" in its place and the error will read differently: "Argument 1 passed to phpwtf() must be an instance of myClass, string given"
(?i)^[ \r\n]*CTR (?i) -- case insensitive -- Remove if case sensitive. [ \r\n] -- ignore space and new lines * -- 0 or more times the same CTR - your starts with string.
if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:
If x and/or y is 2-dimensional, then the corresponding columns will be plotted.
In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:
np.squeez doc: Remove single-dimensional entries from the shape of an array.
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()
But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:
You can either use
<h:outputText value="#{param['id']}" />
or
<h:outputText value="#{request.getParameter('id')}" />
However if you want to pass the parameters to your backing beans, using f:viewParam
is probably what you want. "A view parameter is a mapping between a query string parameter and a model value."
<f:viewParam name="id" value="#{blog.entryId}"/>
This will set the id param of the GET parameter to the blog bean's entryId
field. See http://java.dzone.com/articles/bookmarkability-jsf-2 for the details.
You can do this really easily with ack:
ack -l 'cats' | ack -xl 'dogs'
-l
: return a list of files -x
: take the files from STDIN (the previous search) and only search those filesAnd you can just keep piping until you get just the files you want.
Thought to write a code to demonstrate the isAlive() , getState() methods, this example monitors a thread still it terminates(dies).
package Threads;
import java.util.concurrent.TimeUnit;
public class ThreadRunning {
static class MyRunnable implements Runnable {
private void method1() {
for(int i=0;i<3;i++){
try{
TimeUnit.SECONDS.sleep(1);
}catch(InterruptedException ex){}
method2();
}
System.out.println("Existing Method1");
}
private void method2() {
for(int i=0;i<2;i++){
try{
TimeUnit.SECONDS.sleep(1);
}catch(InterruptedException ex){}
method3();
}
System.out.println("Existing Method2");
}
private void method3() {
for(int i=0;i<1;i++){
try{
TimeUnit.SECONDS.sleep(1);
}catch(InterruptedException ex){}
}
System.out.println("Existing Method3");
}
public void run(){
method1();
}
}
public static void main(String[] args) {
MyRunnable runMe=new MyRunnable();
Thread aThread=new Thread(runMe,"Thread A");
aThread.start();
monitorThread(aThread);
}
public static void monitorThread(Thread monitorMe) {
while(monitorMe.isAlive())
{
try{
StackTraceElement[] threadStacktrace=monitorMe.getStackTrace();
System.out.println(monitorMe.getName() +" is Alive and it's state ="+monitorMe.getState()+" || Execution is in method : ("+threadStacktrace[0].getClassName()+"::"+threadStacktrace[0].getMethodName()+") @line"+threadStacktrace[0].getLineNumber());
TimeUnit.MILLISECONDS.sleep(700);
}catch(Exception ex){}
/* since threadStacktrace may be empty upon reference since Thread A may be terminated after the monitorMe.getStackTrace(); call*/
}
System.out.println(monitorMe.getName()+" is dead and its state ="+monitorMe.getState());
}
}
Although factorials make a nice exercise for the beginning programmer, they're not very useful in most cases, and everyone knows how to write a factorial function, so they're typically not in the average library.
I created this simple example from different search results on the internet.
public static ServiceHost CreateServiceHost(Type serviceInterface, Type implementation)
{
//Create base address
string baseAddress = "net.pipe://localhost/MyService";
ServiceHost serviceHost = new ServiceHost(implementation, new Uri(baseAddress));
//Net named pipe
NetNamedPipeBinding binding = new NetNamedPipeBinding { MaxReceivedMessageSize = 2147483647 };
serviceHost.AddServiceEndpoint(serviceInterface, binding, baseAddress);
//MEX - Meta data exchange
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
serviceHost.Description.Behaviors.Add(behavior);
serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexNamedPipeBinding(), baseAddress + "/mex/");
return serviceHost;
}
Using the above URI I can add a reference in my client to the web service.
\\d{3}
matches any sequence of three digits in Java.
use the include is the easiest way as per
http://www.vistax64.com/powershell/168315-get-childitem-filter-files-multiple-extensions.html
A union query can only have one master ORDER BY
clause, IIRC. To get this, in each query making up the greater UNION
query, add a field that will be the one field you sort by for the UNION
's ORDER BY
.
For instance, you might have something like
SELECT field1, field2, '1' AS union_sort
UNION SELECT field1, field2, '2' AS union_sort
UNION SELECT field1, field2, '3' AS union_sort
ORDER BY union_sort
That union_sort
field can be anything you may want to sort by. In this example, it just happens to put results from the first table first, second table second, etc.
There is no solution to this problem. As of IE11 on Windows 8, Microsoft no longer allows ActiveX plugins to run in its browser space. There is absolutely nothing that a third party developer can do about it.
A similar thing has recently happened with the Chrome browser which no longer supports NPAPI plugins. Instead Chrome only supports PPAPI plugins which are useless for system level tasks once performed by NPAPI plugins.
So developers needing browser support for system interactive plugins can only recommend either the Firefox browser or the ASPS web browser.
Working with content and attr in CSS:
.cryptedmail:after {_x000D_
content: attr(data-name) "@" attr(data-domain) "." attr(data-tld); _x000D_
}
_x000D_
<a href="#" class="cryptedmail"_x000D_
data-name="info"_x000D_
data-domain="example"_x000D_
data-tld="org"_x000D_
onclick="window.location.href = 'mailto:' + this.dataset.name + '@' + this.dataset.domain + '.' + this.dataset.tld; return false;"></a>
_x000D_
When javascript is disabled, just the click event will not work, email is still displayed.
Another interesting approach (at least without a click event) would be to make use of the right-to-left mark to override the writing direction. more about this: https://en.wikipedia.org/wiki/Right-to-left_mark
One way to do it:
Enumerate logical drives using GetLogicalDrives
For each logical drive, open a file named "\\.\X:"
(without the quotes) where X is the logical drive letter.
Call DeviceIoControl
passing the handle to the file opened in the previous step, and the dwIoControlCode
parameter set to IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
:
HANDLE hHandle;
VOLUME_DISK_EXTENTS diskExtents;
DWORD dwSize;
[...]
iRes = DeviceIoControl(
hHandle,
IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
NULL,
0,
(LPVOID) &diskExtents,
(DWORD) sizeof(diskExtents),
(LPDWORD) &dwSize,
NULL);
This returns information of the physical location of a logical volume, as a VOLUME_DISK_EXTENTS
structure.
In the simple case where the volume resides on a single physical drive, the physical drive number is available in diskExtents.Extents[0].DiskNumber
If you already have the databinding in place John Myczek answer is complete.
If not you have at least 2 options I know of if you want to specify the source of your data. (However I am not sure whether or not this is in
line with most guidelines, like MVVM)
option 1: like JohnB said. But I think you should use your own defined collection instead of a weakly typed DataTable (no offense, but you can't tell from the code what each column represents)
xaml.cs
DataContext = myCollection;
//myCollection is a `ICollection<YourType>` preferably
`ObservableCollection<YourType>
- option 2) Declare the name of the Datagrid in xaml
<WpfToolkit:DataGrid Name=dataGrid}>
in xaml.cs
CollectionView myCollectionView =
(CollectionView)CollectionViewSource.GetDefaultView(yourCollection);
dataGrid.ItemsSource = myCollectionView;
If your type has a property FirstName defined, you can then do what John Myczek pointed out.
DataGridTextColumn textColumn = new DataGridTextColumn();
dataColumn.Header = "First Name";
dataColumn.Binding = new Binding("FirstName");
dataGrid.Columns.Add(textColumn);
This obviously doesn't work if you don't know properties you will need to show in your dataGrid, but if that is the case you will have more problems to deal with, and I believe that's out of scope here.
In case you want to see the local variables of a calling function use select-frame
before info locals
E.g.:
(gdb) bt
#0 0xfec3c0b5 in _lwp_kill () from /lib/libc.so.1
#1 0xfec36f39 in thr_kill () from /lib/libc.so.1
#2 0xfebe3603 in raise () from /lib/libc.so.1
#3 0xfebc2961 in abort () from /lib/libc.so.1
#4 0xfebc2bef in _assert_c99 () from /lib/libc.so.1
#5 0x08053260 in main (argc=1, argv=0x8047958) at ber.c:480
(gdb) info locals
No symbol table info available.
(gdb) select-frame 5
(gdb) info locals
i = 28
(gdb)
I know this question is pretty old but just want to share my findings.
My laptop is able to handle program which spawns 25,000
threads and all those threads write some data in MySql database at regular interval of 2 seconds.
I ran this program with 10,000 threads
for 30 minutes continuously
then also my system was stable and I was able to do other normal operations like browsing, opening, closing other programs, etc.
With 25,000 threads
system slows down
but it remains responsive.
With 50,000 threads
system stopped responding
instantly and I had to restart my system manually.
My system details are as follows :
Processor : Intel core 2 duo 2.13 GHz
RAM : 4GB
OS : Windows 7 Home Premium
JDK Version : 1.6
Before running I set jvm argument -Xmx2048m
.
Hope it helps.
Just Improved with Levi answer above -
Rack::Utils.parse_query URI("http://example.com?par=hello&par2=bye").query
For a string like above url, it will return
{ "par" => "hello", "par2" => "bye" }
Since we now have inline javascript snippets I might as well add an interactive example of pre and pos increment. It's not C++ but the concept stays the same.
let A = 1;_x000D_
let B = 1;_x000D_
_x000D_
console.log('A++ === 2', A++ === 2);_x000D_
console.log('++B === 2', ++B === 2);
_x000D_
Others have mentioned the relevel
command which is the best solution if you want to change the base level for all analyses on your data (or are willing to live with changing the data).
If you don't want to change the data (this is a one time change, but in the future you want the default behavior again), then you can use a combination of the C
(note uppercase) function to set contrasts and the contr.treatments
function with the base argument for choosing which level you want to be the baseline.
For example:
lm( Sepal.Width ~ C(Species,contr.treatment(3, base=2)), data=iris )
another way is to provide no cache headers from serverside in the code that generates the response to ajax call:
response.setHeader( "Pragma", "no-cache" );
response.setHeader( "Cache-Control", "no-cache" );
response.setDateHeader( "Expires", 0 );
In case you would like a count all the databases plus a summary, please try this:
SELECT IFNULL(table_schema,'Total') "Database",TableCount
FROM (SELECT COUNT(1) TableCount,table_schema
FROM information_schema.tables
WHERE table_schema NOT IN ('information_schema','mysql')
GROUP BY table_schema WITH ROLLUP) A;
Here is a sample run:
mysql> SELECT IFNULL(table_schema,'Total') "Database",TableCount
-> FROM (SELECT COUNT(1) TableCount,table_schema
-> FROM information_schema.tables
-> WHERE table_schema NOT IN ('information_schema','mysql')
-> GROUP BY table_schema WITH ROLLUP) A;
+--------------------+------------+
| Database | TableCount |
+--------------------+------------+
| performance_schema | 17 |
| Total | 17 |
+--------------------+------------+
2 rows in set (0.29 sec)
Give it a Try !!!
As stated in other responses, the build tools requires the --all
flag to be installed. You also better use a -t
filter flag to avoid installing ALL the packages but there is no way to filter all the build tools.
There are already features requests for these two points in AOSP bug tracker. Feel free to vote for them, this might make them happen some day:
I would like to recommend:
Microsoft Edge Run Wrapper
https://github.com/mihula/RunEdge
You run it this way:
RunEdge.exe [URL]
Examples:
RunEdge.exe http://google.com
RunEdge.exe www.stackoverflow.com
It is not exactly new way how to do it, but it is wrapped as exe file, which could be useful in some situations. For me it is way how to start Edge from IBM Notes Basic client.
Crude, but it works on our system:
<div class="block-share spread-share p-t-md">
<a href="http://www.facebook.com/share.php?u=http://www.voteleavetakecontrol.org/our_affiliates&title=Farmers+for+Britain+have+made+the+sensible+decision+to+Vote+Leave.+Be+part+of+a+better+future+for+us+all.+Please+share!"
target="_blank">
<button class="btn btn-social btn-facebook">
<span class="icon icon-facebook">
</span>
Share on Facebook
</button>
</a>
<a href="https://www.facebook.com/FarmersForBritain" target="_blank">
<button class="btn btn-social btn-facebook">
<span class="icon icon-facebook">
</span>
Like on Facebook
</button>
</a>
</div>
It depends on your mark-up, but it can certainly be made to work, I used the following:
$(document).ready(
function() {
$('td p').slideUp();
$('td h2').click(
function(){
$(this).siblings('p').slideToggle();
}
);
}
);
<table>
<thead>
<tr>
<th>Actor</th>
<th>Which Doctor</th>
<th>Significant companion</th>
</tr>
</thead>
<tbody>
<tr>
<td><h2>William Hartnell</h2></td>
<td><h2>First</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
<td><h2>Susan Foreman</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
</tr>
<tr>
<td><h2>Patrick Troughton</h2></td>
<td><h2>Second</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
<td><h2>Jamie MacCrimmon</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
</tr>
<tr>
<td><h2>Jon Pertwee</h2></td>
<td><h2>Third</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
<td><h2>Jo Grant</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
</tr>
</tbody>
</table>
The way I approached it is to collapse specific elements within the cells of the row, so that, in my case, the row would slideUp()
as the paragraphs were hidden, and still leave an element, h2
to click on in order to re-show the content. If the row collapsed entirely there'd be no easily obvious way to bring it back.
As @Peter Ajtai noted, in the comments, the above approach focuses on only one cell (though deliberately). To expand all the child p
elements this would work:
$(document).ready(
function() {
$('td p').slideUp();
$('td h2').click(
function(){
$(this).closest('tr').find('p').slideToggle();
}
);
}
);
Return false will stop the hyperlink being followed after the javascript has run. This is useful for unobtrusive javascript that degrades gracefully - for example, you could have a thumbnail image that uses javascript to open a pop-up of the full-sized image. When javascript is turned off or the image is middle-clicked (opened in a new tab) this ignores the onClick event and just opens the image as a full-sized image normally.
If return false were not specified, the image would both launch the pop-up and open the image normally. Some people instead of using return false use javascript as the href attribute, but this means that when javascript is disabled the link will do nothing.
I found this;
from here;
vba- Can a combobox present more then one column on it's textbox part?
and this may help;
I added a sort of demo here;
http://digital.ni.com/public.nsf/allkb/4EA929B78B5718238625789D0071F307
This error occurs because the default value is true for the Embed Interop Types property of the TestStand API Interop assembly referenced in the new project. To resolve this error, change the value of the Embed Interop Types property to False by following these steps: Select the TestStand Interop Assembly reference in the references section of your project in the Solution Explorer. Find the Embed Interop Types property in the Property Browser, and change the value to False
Here is what I did to solve just by 2 ways:
make ID column as int
type
if you are using autogenerate in ID dont assing value in the setter of ID. If your mapping the some then sometimes autogenetated ID is not concedered. (I dont know why)
try using @GeneratedValue(strategy=GenerationType.SEQUENCE)
if possible
Use This This Will work For sure
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class ProtectedConfigFile {
private static final char[] PASSWORD = "enfldsgbnlsngdlksdsgm".toCharArray();
private static final byte[] SALT = { (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12, (byte) 0xde, (byte) 0x33,
(byte) 0x10, (byte) 0x12, };
public static void main(String[] args) throws Exception {
String originalPassword = "Aman";
System.out.println("Original password: " + originalPassword);
String encryptedPassword = encrypt(originalPassword);
System.out.println("Encrypted password: " + encryptedPassword);
String decryptedPassword = decrypt(encryptedPassword);
System.out.println("Decrypted password: " + decryptedPassword);
}
private static String encrypt(String property) throws GeneralSecurityException, UnsupportedEncodingException {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
return base64Encode(pbeCipher.doFinal(property.getBytes("UTF-8")));
}
private static String base64Encode(byte[] bytes) {
// NB: This class is internal, and you probably should use another impl
return new BASE64Encoder().encode(bytes);
}
private static String decrypt(String property) throws GeneralSecurityException, IOException {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
return new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
}
private static byte[] base64Decode(String property) throws IOException {
// NB: This class is internal, and you probably should use another impl
return new BASE64Decoder().decodeBuffer(property);
}
}
To remove duplicates from a single column
Sub removeDuplicate()
'removeDuplicate Macro
Columns("A:A").Select
ActiveSheet.Range("$A$1:$A$117").RemoveDuplicates Columns:=Array(1), _
Header:=xlNo
Range("A1").Select
End Sub
if you have header then use Header:=xlYes
Increase your range as per your requirement.
you can make it to 1000 like this :
ActiveSheet.Range("$A$1:$A$1000")
More info here here
Label's aren't form elements. They don't have a value
. They have innerHTML
and textContent
.
Thus,
$('#telefon').html()
// or
$('#telefon').text()
or
var telefon = document.getElementById('telefon');
telefon.innerHTML;
If you are starting with your form element, check out the labels
list of it. That is,
var el = $('#myformelement');
var label = $( el.prop('labels') );
// label.html();
// el.val();
// blah blah blah you get the idea
Use patchValue()
method which helps to update even subset of controls.
setValue(){
this.editqueForm.patchValue({user: this.question.user, questioning: this.question.questioning})
}
setValue()
method:
Error When strict checks fail, such as setting the value of a control that doesn't exist or if you excluding the value of a control.
In your case, object missing options
and questionType
control value so setValue()
will fail to update.
Here is one breakdown:
Front-end tier -> User Interface layer usually consisting of a mix of HTML, Javascript, CSS, Flash, and various server-side code like ASP.Net, classic ASP, PHP, etc. Think of this as being closest to the user in terms of code.
Middleware, middle-tier -> One tier back, generally referred to as the "plumbing" part of a system. Java and C# are common languages for writing this part that could be viewed as the glue between the UI and the data and can be webservices or WCF components or other SOA components possibly.
Back-end tier -> Databases and other data stores are generally at this level. Oracle, MS-SQL, MySQL, SAP, and various off-the-shelf pieces of software come to mind for this piece of software that is the final processing of the data.
Overlap can exist between any of these as you could have everything poured into one layer like an ASP.Net website that uses the built-in AJAX functionality that generates Javascript while the code behind may contain database commands making the code behind contain both middle and back-end tiers. Alternatively, one could use VBScript to act as all the layers using ADO objects and merging all three tiers into one.
Similarly, taking middleware and either front or back-end can be combined in some cases.
Bottlenecks generally have a few different levels to them:
1) Database or back-end processing -> This can vary from payroll or sales or other tasks where the throughput to the database is bogging things down.
2) Middleware bottlenecks -> This would be where some web service may be hitting capacity but the front and back ends have bandwidth to handle more traffic. Alternatively, there may be some server that is part of a system that isn't quite the UI part or the raw data that can be a bottleneck using something like Biztalk or MSMQ.
3) Front-end bottlenecks -> This could client or server-side issues. For example, if you took a low-end PC and had it load a web page that consisted of a lot of data being downloaded, the client could be where the bottleneck is. Similarly, the server could be queuing up requests if it is getting hammered with requests like what Amazon.com or other high-traffic websites may get at times.
Some of this is subject to interpretation, so it isn't perfect by any means and YMMV.
EDIT: Something to consider is that some systems can have multiple front-ends or back-ends. For example, a content management system will likely have a way for site visitors to view the content that is a front-end but what about how content editors are able to change the data on the site? The ability to pull up this data could be seen as front-end since it is a UI component or it could be seen as a back-end since it is used by internal users rather than the general public viewing the site. Thus, there is something to be said for context here.
Vim has a branch operator \&
that is useful when searching for a line containing a set of words, in any order. Moreover, extending the set of required words is trivial.
For example,
/.*jack\&.*james
will match a line containing jack
and james
, in any order.
See this answer for more information on usage. I am not aware of any other regex flavor that implements branching; the operator is not even documented on the Regular Expression wikipedia entry.
This saves you having to duplicate the link in the tr - just fish it out of the first a.
$(".link-first-found").click(function() {
var href;
href = $(this).find("a").attr("href");
if (href !== "") {
return document.location = href;
}
});
Even with these answers it took me three days to figure out what was going on and I may need the solution again in the future.
My situation was slightly different from the one described.
In mine, I had some contenteditable text in a div on the page. When the user clicked on a DIFFERENT div, a button of sorts, I automatically selected some text in the contenteditable div (a selection range that had previously been saved and cleared), ran a rich text execCommand on that selection, and cleared it again.
This enabled me to invisibly change text colors based on user interactions with color divs elsewhere on the page, while keeping the selection normally hidden to let them see the colors in the proper context.
Well, on iPad's Safari, clicking the color div resulted in the on-screen keyboard coming up, and nothing I did would prevent it.
I finally figured out how the iPad's doing this.
It listens for a touchstart and touchend sequence that triggers a selection of editable text.
When that combination happens, it shows the on-screen keyboard.
Actually, it does a dolly zoom where it expands the underlying page while zooming in on the editable text. It took me a day just to understand what I was seeing.
So the solution I used was to intercept both touchstart and touchend on those particular color divs. In both handlers I stop propagation and bubbling and return false. But in the touchend event I trigger the same behavior that click triggered.
So, before, Safari was triggering what I think was "touchstart", "mousedown", "touchend", "mouseup", "click", and because of my code, a text selection, in that order.
The new sequence because of the intercepts is simply the text selection. Everything else gets intercepted before Safari can process it and do its keyboard stuff. The touchstart and touchend intercepts prevent the mouse events from triggering as well, and in context this is totally fine.
I don't know an easier way to describe this but I think it's important to have it here because I found this thread within an hour of first encountering the issue.
I'm 98% sure the same fix will work with input boxes and anything else. Intercept the touch events and process them separately without letting them propagate or bubble, and consider doing any selections after a tiny timeout just to make sure Safari doesn't recognize the sequence as the keyboard trigger.
If, by Boolean AND, you mean items that appear in both lists, e.g. intersection, then you should look at Python's set
and frozenset
types.
Roman, if you want to do your layout in Java code (ViewGroup descendant), it is possible. The trick is that you have to implement both onMeasure and onLayout methods. The onMeasure gets called first and you need to "measure" the subview (effectively sizing it to the desired value) there. You need to size it again in the onLayout call. If you fail to do this sequence or fail to call setMeasuredDimension() at the end of your onMeasure code, you won't get results. Why is this designed in such complicated and fragile way is beyond me.
While moopasta's answer works, it doesn't appear to allow wildcards and there is another (potentially better) option. The Chromium project has some HTTP authentication documentation that is useful but incomplete.
Specifically the option that I found best is to whitelist sites that you would like to allow Chrome to pass authentication information to, you can do this by:
auth-server-whitelist
command line switch. e.g. --auth-server-whitelist="*example.com,*foobar.com,*baz"
. Downfall to this approach is that opening links from other programs will launch Chrome without the command line switch.AuthServerWhitelist
/"Authentication server whitelist" Group Policy or Local Group Policy. This seems like the most stable option but takes more work to setup. You can set this up locally, no need to have this remotely deployed.Those looking to set this up for an enterprise can likely follow the directions for using Group Policy or the Admin console to configure the AuthServerWhitelist
policy. Those looking to set this up for one machine only can also follow the Group Policy instructions:
Start > Run > gpedit.msc
Local Computer Policy > Computer Configuration > Administrative Templates
Administrative Templates
, and select Add/Remove Templates
windows\adm\en-US\chrome.adm
template via the dialogComputer Configuration > Administrative Templates > Classic Administrative Templates > Google > Google Chrome > Policies for HTTP Authentication
enable and configure Authentication server whitelist
chrome://policy
to view active policiesIn order to do this you need to attach the handler to a specific anchor on the page. For operations like this it's much easier to use a standard framework like jQuery. For example if I had the following HTML
HTML:
<a id="theLink">Click Me</a>
I could use the following jQuery to hookup an event to that specific link.
// Use ready to ensure document is loaded before running javascript
$(document).ready(function() {
// The '#theLink' portion is a selector which matches a DOM element
// with the id 'theLink' and .click registers a call back for the
// element being clicked on
$('#theLink').click(function (event) {
// This stops the link from actually being followed which is the
// default action
event.preventDefault();
var answer confirm("Please click OK to continue");
if (!answer) {
window.location="http://www.continue.com"
}
});
});
You can use this repo: GSBorderLabel
It's quite simple:
GSBorderLabel *myLabel = [[GSBorderLabel alloc] initWithTextColor:aColor
andBorderColor:anotherColor
andBorderWidth:2];
It is useful when you share a variable between a few modules. You define it in one module, and use extern in the others.
For example:
in file1.cpp:
int global_int = 1;
in file2.cpp:
extern int global_int;
//in some function
cout << "global_int = " << global_int;
strToLower should return a char * instead of a char. Something like this would do.
char *strToLower(char *cString)
You could use Extension
method to switch between Regular Style and Bold Style as below:
static class Helper
{
public static void SwtichToBoldRegular(this TextBox c)
{
if (c.Font.Style!= FontStyle.Bold)
c.Font = new Font(c.Font, FontStyle.Bold);
else
c.Font = new Font(c.Font, FontStyle.Regular);
}
}
And usage:
textBox1.SwtichToBoldRegular();
<?php
$con = mysql_connect("server.com","user","pswd");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("select count(1) FROM table");
$row = mysql_fetch_array($result);
$total = $row[0];
echo "Total rows: " . $total;
mysql_close($con);
?>
This will fail though if the string can contain strings like "miscontrue".
Regex.Matches("7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false", "true").Count;
Restart the visual studio as Admin will work on in many cases.
If you don't want to clutter up your console with error messages, you can also run
git ls-files file_name
and then check the result. If git returns nothing, then the file is not tracked. If it's tracked, git will return the file path.
This comes in handy if you want to combine it in a script, for example PowerShell:
$gitResult = (git ls-files $_) | out-string
if ($gitResult.length -ne 0)
{
## do stuff with the tracked file
}
I'd recommend this article on CSS Tricks by Chris Coyier entitled Better Helvetica:
http://css-tricks.com/snippets/css/better-helvetica/
He basically recommends the following declaration for covering all the bases:
body {
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
font-weight: 300;
}
$new_input = array('type' => 'text', 'label' => 'First name', 'show' => true, 'required' => true);
$options['inputs']['name'] = $new_input;
Note: Not in boolean
WebDriver driver=new FirefoxDriver();
driver.get("http://www.gmail.com");
if(driver.getPageSource().contains("Ur message"))
{
System.out.println("Pass");
}
else
{
System.out.println("Fail");
}
public static String currencyFormat(BigDecimal n) {
return NumberFormat.getCurrencyInstance().format(n);
}
It will use your JVM’s current default Locale
to choose your currency symbol. Or you can specify a Locale
.
NumberFormat.getInstance(Locale.US)
For more info, see NumberFormat
class.
A new byte array will automatically be initialized with all zeroes. You don't have to do anything.
The more general approach to initializing with other values, is to use the Arrays
class.
import java.util.Arrays;
byte[] bytes = new byte[100];
Arrays.fill( bytes, (byte) 1 );
echo -e "YOURPASSWORD\n" | sudo -S yourcommand
Short answer:
Context context;
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
context = recyclerView.getContext();
}
Explanation why other answers are not great:
Context
to the adapter is completely unnecessary, since RecyclerView
you can access it from inside the classContext
at ViewHolder
level means that you do it every time you bind or create a ViewHolder
. You duplicate operations.Activity
lifespan (which would be weird) then you already have a leak.I also had same problem. Purposely my build output path was "..\bin" and it works for me when I set the build output path as "\bin".
npm
for managing client-side libraries is a good choice (as opposed to Bower or NuGet), you're thinking in the right direction :)FileServer
, having StaticFiles
should suffice for serving static files (.js, images, etc.)wwwroot
to public
, otherwise the folder structure in Azure Web Apps will be confusing (D:\Home\site\wwwroot\wwwroot
vs D:\Home\site\wwwroot\public
)node_modules
to a web hosting server). See tools/deploy.js
as an example.Visit ASP.NET Core Starter Kit on GitHub (disclaimer: I'm the author)
If you also want to keep hash and get parameter, you can do something like this (fill redirectMap at filter init):
String uri = request.getRequestURI();
String[] uriParts = uri.split("[#?]");
String path = uriParts[0];
String rest = uri.substring(uriParts[0].length());
if(redirectMap.containsKey(path)) {
response.sendRedirect(redirectMap.get(path) + rest);
} else {
chain.doFilter(request, response);
}
Note: In hindsight this was a quick and dirty answer, and may not work in all situations. To have a reliable solution, see Tim Down's answer (copy pasting that here as this answer is still getting views and upvotes):
You can't do this reliably with the keyup event. If you want to know something about the character that was typed, you have to use the keypress event instead.
The following example will work all the time in most browsers but there are some edge cases that you should be aware of. For what is in my view the definitive guide on this, see http://unixpapa.com/js/key.html.
$("input").keypress(function(e) { if (e.which !== 0) { alert("Character was typed. It was: " + String.fromCharCode(e.which)); } });
keyup
andkeydown
give you information about the physical key that was pressed. On standard US/UK keyboards in their standard layouts, it looks like there is a correlation between thekeyCode
property of these events and the character they represent. However, this is not reliable: different keyboard layouts will have different mappings.
The following was the original answer, but is not correct and may not work reliably in all situations.
To match the keycode with a word character (eg., a
would match. space
would not)
$("input").keyup(function(event)
{
var c= String.fromCharCode(event.keyCode);
var isWordcharacter = c.match(/\w/);
});
Ok, that was a quick answer. The approach is the same, but beware of keycode issues, see this article in quirksmode.
For those who are looking for a date-only solution, it is:
import datetime
datetime.date.today().isoformat()
I had this problem and
dumpbin /exports mydll.dll
and
depends mydll.dll
showed 'DllRegisterServer'.
The problem was that there was another DLL in the system that had the same name. After renaming mydll the registration succeeded.
Here's another solution using a package solely dedicated to working with dates and times in R:
library(tidyverse)
library(lubridate)
(df <- tibble(ID = 1:3, Date = c("2004-02-06" , "2006-03-14", "2007-07-16")))
#> # A tibble: 3 x 2
#> ID Date
#> <int> <chr>
#> 1 1 2004-02-06
#> 2 2 2006-03-14
#> 3 3 2007-07-16
df %>%
mutate(
Date = ymd(Date),
Month_Yr = format_ISO8601(Date, precision = "ym")
)
#> # A tibble: 3 x 3
#> ID Date Month_Yr
#> <int> <date> <chr>
#> 1 1 2004-02-06 2004-02
#> 2 2 2006-03-14 2006-03
#> 3 3 2007-07-16 2007-07
Created on 2020-09-01 by the reprex package (v0.3.0)
A solution without jQuery for the most popular answer:
document.addEventListener('mouseup', function (e) {
var container = document.getElementById('your container ID');
if (!container.contains(e.target)) {
container.style.display = 'none';
}
}.bind(this));
MDN: https://developer.mozilla.org/en/docs/Web/API/Node/contains
You can use the :checkbox
and :checked
pseudo-selectors and the .class
selector, with that you will make sure that you are getting the right elements, only checked checkboxes with the class you specify.
Then you can easily use the Traversing/map method to get an array of values:
var values = $('input:checkbox:checked.group1').map(function () {
return this.value;
}).get(); // ["18", "55", "10"]
>>> from collections import OrderedDict
>>> OrderedDict([('method', 'constant'), ('data', '1.225')])
OrderedDict([('method', 'constant'), ('data', '1.225')])
>>> dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))
{'data': '1.225', 'method': 'constant'}
>>>
However, to store it in a database it'd be much better to convert it to a format such as JSON or Pickle. With Pickle you even preserve the order!
Your font
tag is not correct, so it won't work in some browsers. The px
unit is used with CSS, not HTML attributes. The font tag should look like this:
<font size="100">
Well, actually it shouldn't be there at all. The font
tag is deprecated, you should use CSS to style the content, like you do already with the text-decoration
:
<a href="selectTopic?html" style="font-size: 100px; text-decoration: none">HTML 5</a>
To separate the content from the styling, you should of course work towards putting the CSS in a style sheet rather than as inline style
attributes. That way you can apply one style to several elements without having to put the same style
attribute in all of them.
Example:
<a href="selectTopic?html" class="topic">HTML 5</a>
CSS:
.topic { font-size: 100px; text-decoration: none; }
What you're doing will work, and the browser will receive a 404 code. What it won't do is display the "not found" page that you might be expecting, e.g.:
The requested URL /test.php was not found on this server.
That's because the web server doesn't send that page when PHP returns a 404 code (at least Apache doesn't). PHP is responsible for sending all its own output. So if you want a similar page, you'll have to send the HTML yourself, e.g.:
<?php
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);
include("notFound.php");
?>
You could configure Apache to use the same page for its own 404 messages, by putting this in httpd.conf:
ErrorDocument 404 /notFound.php
There are 2 main reasons for __init__.py
For convenience: the other users will not need to know your functions' exact location in your package hierarchy.
your_package/
__init__.py
file1.py
file2.py
...
fileN.py
# in __init__.py
from file1 import *
from file2 import *
...
from fileN import *
# in file1.py
def add():
pass
then others can call add() by
from your_package import add
without knowing file1, like
from your_package.file1 import add
If you want something to be initialized; for example, logging (which should be put in the top level):
import logging.config
logging.config.dictConfig(Your_logging_config)
To skip the test case during maven clean install i used -DskipTests paramater in following command
mvn clean install -DskipTests
into terminal window
From Java 8 you can use :
Comparator.comparingInt(Dog::getDogAge).reversed();
Add the following under @NgModule({})
in 'app.module.ts' :
import {CUSTOM_ELEMENTS_SCHEMA} from `@angular/core`;
and then
schemas: [
CUSTOM_ELEMENTS_SCHEMA
]
Your 'app.module.ts' should look like this:
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
@NgModule({
declarations: [],
imports: [],
schemas: [ CUSTOM_ELEMENTS_SCHEMA],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
You can also push markers into an array. See code example, this works for me:
/*create array:*/
var marker = new Array();
/*Some Coordinates (here simulating somehow json string)*/
var items = [{"lat":"51.000","lon":"13.000"},{"lat":"52.000","lon":"13.010"},{"lat":"52.000","lon":"13.020"}];
/*pushing items into array each by each and then add markers*/
function itemWrap() {
for(i=0;i<items.length;i++){
var LamMarker = new L.marker([items[i].lat, items[i].lon]);
marker.push(LamMarker);
map.addLayer(marker[i]);
}
}
/*Going through these marker-items again removing them*/
function markerDelAgain() {
for(i=0;i<marker.length;i++) {
map.removeLayer(marker[i]);
}
}
does this example help ?
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
using (StreamWriter output = new StreamWriter("practice.txt"))
{
// Create and write a string containing the symbol for Pi.
string srcString = "Area = \u03A0r^2";
// Convert the UTF-16 encoded source string to UTF-8 and ASCII.
byte[] utf8String = Encoding.UTF8.GetBytes(srcString);
byte[] asciiString = Encoding.ASCII.GetBytes(srcString);
// Write the UTF-8 and ASCII encoded byte arrays.
output.WriteLine("UTF-8 Bytes: {0}", BitConverter.ToString(utf8String));
output.WriteLine("ASCII Bytes: {0}", BitConverter.ToString(asciiString));
// Convert UTF-8 and ASCII encoded bytes back to UTF-16 encoded
// string and write.
output.WriteLine("UTF-8 Text : {0}", Encoding.UTF8.GetString(utf8String));
output.WriteLine("ASCII Text : {0}", Encoding.ASCII.GetString(asciiString));
Console.WriteLine(Encoding.UTF8.GetString(utf8String));
Console.WriteLine(Encoding.ASCII.GetString(asciiString));
}
}
}
You can't use UIImagePickerController
, but you can use a custom image picker. I think ELCImagePickerController
is the best option, but here are some other libraries you could use:
Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection
Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker
Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.
This problem can also occur when you have conflicting tags. If your local version and remote version use same tag name for different commits, you can end up here.
You can solve it my deleting the local tag:
$ git tag --delete foo_tag
Since Java 10 it is possible to use
Map.copyOf
for creating a shallow copy, which is also immutable. (Here is its Javadoc). For a deep copy, as mentioned in this answer you, need some kind of value mapper to make a safe copy of values. You don't need to copy keys though, since they must be immutable.
Complicated way but works:
$num = '125.0100';
$index = $num[strlen($num)-1];
$i = strlen($num)-1;
while($index == '0') {
if ($num[$i] == '0') {
$num[$i] = '';
$i--;
}
$index = $num[$i];
}
//remove dot if no numbers exist after dot
$explode = explode('.', $num);
if (isset($explode[1]) && intval($explode[1]) <= 0) {
$num = intval($explode[0]);
}
echo $num; //125.01
the solutions above are the optimal way but in case you want to have your own you could use this. What this algorithm does it starts at the end of string and checks if its 0, if it is it sets to empty string and then goes to the next character from back untill the last character is > 0
First create a <span id="decodeIt" style="display:none;"></span>
somewhere in the body
Next, assign the string to be decoded as innerHTML to this:
document.getElementById("decodeIt").innerHTML=stringtodecode
Finally,
stringtodecode=document.getElementById("decodeIt").innerText
Here is the overall code:
var stringtodecode="<B>Hello</B> world<br>";
document.getElementById("decodeIt").innerHTML=stringtodecode;
stringtodecode=document.getElementById("decodeIt").innerText
reloadData is no good because there's no animation...
This is what I'm currently trying:
NSArray* paths = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]];
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];
[self.tableView deleteRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];
It almost works right. Almost. I'm increasing the height of the cell, and sometimes there's a little "hiccup" in the table view as the cell is replaced, as if some scrolling position in the table view is being preserved, the new cell (which is the first cell in the table) ends up with its offset too high, and the scrollview bounces to reposition it.
Try this:
if (MessageBox.Show("Are you sure", "Title_here", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
Do something here for 'Yes'...
}
A li doesn't have a value. Only form-related elements such as input, textarea and select have values.
Sometimes the command that cron needs to run is in a directory where cron has no access, typically on systems where users' home directories' permissions are 700 and the command is in that directory.
I had the same problem. It works perfectly fine when you add this:
android:inputType="textFilter"
to your EditText
.
SELECT MAX(col) +1
is not safe -- it does not ensure that you aren't inserting more than one customer with the same customer_id
value, regardless if selecting from the same table or any others. The proper way to ensure a unique integer value is assigned on insertion into your table in MySQL is to use AUTO_INCREMENT. The ANSI standard is to use sequences, but MySQL doesn't support them. An AUTO_INCREMENT column can only be defined in the CREATE TABLE statement:
CREATE TABLE `customers` (
`customer_id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(45) DEFAULT NULL,
`surname` varchar(45) DEFAULT NULL,
PRIMARY KEY (`customer_id`)
)
That said, this worked fine for me on 5.1.49:
CREATE TABLE `customers` (
`customer_id` int(11) NOT NULL DEFAULT '0',
`firstname` varchar(45) DEFAULT NULL,
`surname` varchar(45) DEFAULT NULL,
PRIMARY KEY (`customer_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
INSERT INTO customers VALUES (1, 'a', 'b');
INSERT INTO customers
SELECT MAX(customer_id) + 1, 'jim', 'sock'
FROM CUSTOMERS;
You generally shouldn't use e.g. const int
in a header file, if it's included in several source files. That is because then the variables will be defined once per source file (translation units technically speaking) because global const
variables are implicitly static, taking up more memory than required.
You should instead have a special source file, Constants.cpp
that actually defines the variables, and then have the variables declared as extern
in the header file.
Something like this header file:
// Protect against multiple inclusions in the same source file
#ifndef CONSTANTS_H
#define CONSTANTS_H
extern const int CONSTANT_1;
#endif
And this in a source file:
const int CONSTANT_1 = 123;
I have taken three Views. In the first view I set full (no alpha) color, on the second view I set half (0.5 alpha) color, and on the third view I set light color (0.2 alpha).
You can set any color and get color with alpha by using the below code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:gravity = "center"
android:orientation = "vertical"
tools:context = "com.example.temp.MainActivity" >
<View
android:id = "@+id/fullColorView"
android:layout_width = "100dip"
android:layout_height = "100dip" />
<View
android:id = "@+id/halfalphaColorView"
android:layout_width = "100dip"
android:layout_height = "100dip"
android:layout_marginTop = "20dip" />
<View
android:id = "@+id/alphaColorView"
android:layout_width = "100dip"
android:layout_height = "100dip"
android:layout_marginTop = "20dip" />
</LinearLayout>
public class MainActivity extends Activity {
private View fullColorView, halfalphaColorView, alphaColorView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fullColorView = (View)findViewById(R.id.fullColorView);
halfalphaColorView = (View)findViewById(R.id.halfalphaColorView);
alphaColorView = (View)findViewById(R.id.alphaColorView);
fullColorView.setBackgroundColor(Color.BLUE);
halfalphaColorView.setBackgroundColor(getColorWithAlpha(Color.BLUE, 0.5f));
alphaColorView.setBackgroundColor(getColorWithAlpha(Color.BLUE, 0.2f));
}
private int getColorWithAlpha(int color, float ratio) {
int newColor = 0;
int alpha = Math.round(Color.alpha(color) * ratio);
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
newColor = Color.argb(alpha, r, g, b);
return newColor;
}
}
Kotlin version:
private fun getColorWithAlpha(color: Int, ratio: Float): Int {
return Color.argb(Math.round(Color.alpha(color) * ratio), Color.red(color), Color.green(color), Color.blue(color))
}
Done
In case if you use new swift version.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ChannelMoreSegue" {
}
}
As others have stated, regular (traditional) functions use this
from the object that called the function, (e.g. a button that was clicked). Instead, arrow functions use this
from the object that defines the function.
Consider two almost identical functions:
regular = function() {
' Identical Part Here;
}
arrow = () => {
' Identical Part Here;
}
The snippet below demonstrates the fundamental difference between what this
represents for each function. The regular function outputs [object HTMLButtonElement]
whereas the arrow function outputs [object Window]
.
<html>_x000D_
<button id="btn1">Regular: `this` comes from "this button"</button>_x000D_
<br><br>_x000D_
<button id="btn2">Arrow: `this` comes from object that defines the function</button>_x000D_
<p id="res"/>_x000D_
_x000D_
<script>_x000D_
regular = function() {_x000D_
document.getElementById("res").innerHTML = this;_x000D_
}_x000D_
_x000D_
arrow = () => {_x000D_
document.getElementById("res").innerHTML = this;_x000D_
}_x000D_
_x000D_
document.getElementById("btn1").addEventListener("click", regular);_x000D_
document.getElementById("btn2").addEventListener("click", arrow);_x000D_
</script>_x000D_
</html>
_x000D_
RenderPartial()
is a void method that writes to the response stream. A void method, in C#, needs a ;
and hence must be enclosed by { }
.
Partial()
is a method that returns an MvcHtmlString. In Razor, You can call a property or a method that returns such a string with just a @
prefix to distinguish it from plain HTML you have on the page.
You could use deepflatten
from the 3rd party package iteration_utilities
:
>>> from iteration_utilities import deepflatten
>>> L = [[[1, 2, 3], [4, 5]], 6]
>>> list(deepflatten(L))
[1, 2, 3, 4, 5, 6]
>>> list(deepflatten(L, types=list)) # only flatten "inner" lists
[1, 2, 3, 4, 5, 6]
It's an iterator so you need to iterate it (for example by wrapping it with list
or using it in a loop). Internally it uses an iterative approach instead of an recursive approach and it's written as C extension so it can be faster than pure python approaches:
>>> %timeit list(deepflatten(L))
12.6 µs ± 298 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
>>> %timeit list(deepflatten(L, types=list))
8.7 µs ± 139 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
>>> %timeit list(flatten(L)) # Cristian - Python 3.x approach from https://stackoverflow.com/a/2158532/5393381
86.4 µs ± 4.42 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit list(flatten(L)) # Josh Lee - https://stackoverflow.com/a/2158522/5393381
107 µs ± 2.99 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit list(genflat(L, list)) # Alex Martelli - https://stackoverflow.com/a/2159079/5393381
23.1 µs ± 710 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
I'm the author of the iteration_utilities
library.
Simple jQuery, PHP and JSONP example is below:
window.onload = function(){_x000D_
$.ajax({_x000D_
cache: false,_x000D_
url: "https://jsonplaceholder.typicode.com/users/2",_x000D_
dataType: 'jsonp',_x000D_
type: 'GET',_x000D_
success: function(data){_x000D_
console.log('data', data)_x000D_
},_x000D_
error: function(data){_x000D_
console.log(data);_x000D_
}_x000D_
});_x000D_
};
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
The read
method returns a sequence of bytes as a string. To convert from a string byte-sequence to binary data, use the built-in struct
module: http://docs.python.org/library/struct.html.
import struct
print(struct.unpack('i', fin.read(4)))
Note that unpack
always returns a tuple, so struct.unpack('i', fin.read(4))[0]
gives the integer value that you are after.
You should probably use the format string '<i'
(< is a modifier that indicates little-endian byte-order and standard size and alignment - the default is to use the platform's byte ordering, size and alignment). According to the BMP format spec, the bytes should be written in Intel/little-endian byte order.
Try this
<allow users="?" />
Now you are using <deny users="?" />
that means you are not allowing authenticated user to use your site.
This solution essentially draws the image as 'aspect fit' within the given rect.
CGSize itemSize = CGSizeMake(80, 80);
UIGraphicsBeginImageContextWithOptions(itemSize, NO, UIScreen.mainScreen.scale);
UIImage *image = cell.imageView.image;
CGRect imageRect;
if(image.size.height > image.size.width) {
CGFloat width = itemSize.height * image.size.width / image.size.height;
imageRect = CGRectMake((itemSize.width - width) / 2, 0, width, itemSize.height);
} else {
CGFloat height = itemSize.width * image.size.height / image.size.width;
imageRect = CGRectMake(0, (itemSize.height - height) / 2, itemSize.width, height);
}
[cell.imageView.image drawInRect:imageRect];
cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
It'd be better to use List<T>.RemoveAll to accomplish this.
authorsList.RemoveAll((x) => x.firstname == "Bob");
Use restart: always in your docker compose file.
Docker-compose up -d
will launch container from images again. Use docker-compose start
to start the stopped containers, it never launches new containers from images.
nginx:
restart: always
image: nginx
ports:
- "80:80"
- "443:443" links:
- other_container:other_container
Also you can write the code up in the docker file so that it gets created first, if it has the dependency of other containers.
<b>
and <i>
are explicit - they specify bold and italic respectively.
<strong>
and <em>
are semantic - they specify that the enclosed text should be "strong" or "emphasised" in some way, usually bold and italic, but allow for the actual styling to be controlled via CSS. Hence these are preferred in modern web pages.
You could use negative lookahead, or something like this:
^([^A]|A([^B]|B([^C]|$)|$)|$).*$
Maybe it could be simplified a bit.
Have you tried the uncurl
package (https://github.com/spulec/uncurl)? You can install it via pip, pip install uncurl
. Your curl request returns:
>>> uncurl "curl --header \"Authorization:access_token myToken\" https://website.com/id"
requests.get("https://website.com/id",
headers={
"Authorization": "access_token myToken"
},
cookies={},
)
Take a look at UIScreen.
eg.
CGFloat width = [UIScreen mainScreen].bounds.size.width;
Take a look at the applicationFrame property if you don't want the status bar included (won't affect the width).
UPDATE: It turns out UIScreen (-bounds or -applicationFrame) doesn't take into account the current interface orientation. A more correct approach would be to ask your UIView for its bounds -- assuming this UIView has been auto-rotated by it's View controller.
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
CGFloat width = CGRectGetWidth(self.view.bounds);
}
If the view is not being auto-rotated by the View Controller then you will need to check the interface orientation to determine which part of the view bounds represents the 'width' and the 'height'. Note that the frame property will give you the rect of the view in the UIWindow's coordinate space which (by default) won't be taking the interface orientation into account.
use this: String customHtml =text ;
wb.loadDataWithBaseURL(null,customHtml,"text/html", "UTF-8", null);
For example:
$('html, body').scrollTop($(document).height());
Google, no API needed:
$data = file_get_contents('http://picasaweb.google.com/data/entry/api/user/<USER_ID>?alt=json');
$d = json_decode($data);
$avatar = $d->{'entry'}->{'gphoto$thumbnail'}->{'$t'};
// Outputs example: https://lh3.googleusercontent.com/-2N6fRg5OFbM/AAAAAAAAAAI/AAAAAAAAADE/2-RmpExH6iU/s64-c/photo.jpg
CHANGE: the 64 in "s64" for the size
If your repo have 2FA enabled. Highly suggest to use the app provided by github.com Here is the link: https://desktop.github.com/
After you downloaded it and installed it. Follow the withard, the app will ask you to provide the one time password for login. Once you filled in the one time password, you could see your repo/projects now.
I had the same issue when updating an older project. Here's what I did to resolve it:
The projects that used Entity Framework 5 and .NET 4 were installing the Entity Framework dll version 4.4. Once I switched the .NET version to 4.5 on the project, the dll version would be 5.
My problem came from older projects being on .NET 4 and a newer project running .NET 4.5 so there were 2 dll versions of EF in my solution.
Hope this helps someone...
You can find out what library depends on a wrong version of the support library and exclude it like this:
compile ('com.stripe:stripe-android:5.1.1') {
exclude group: 'com.android.support'
}
stripe-android
in my case.