I think I also have this problem, I was trying to make calendar visible after clicking a button but the page keeps refreshing after clicking the button
MaintainScrollPositionOnPostBack="true"
This actually answered my problem.
I cant vote or comment, I just joined SO today
Based on posted answered, this worked for me:
/* check for iOS 6 or 7 */
if ([[self navigationController].navigationBar respondsToSelector:@selector(setBarTintColor:)]) {
[[self navigationController].navigationBar setBarTintColor:[UIColor whiteColor]];
} else {
/* Set background and foreground */
[[self navigationController].navigationBar setTintColor:[UIColor whiteColor]];
[self navigationController].navigationBar.titleTextAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:[UIColor blackColor],UITextAttributeTextColor,nil];
}
I found the solution.
As said in the EDIT of my answer, a <div>
is misfunctioning in a <table>
.
So I wrote this code instead :
<tr id="hidden" style="display:none;">
<td class="depot_table_left">
<label for="sexe">Sexe</label>
</td>
<td>
<select type="text" name="sexe">
<option value="1">Sexe</option>
<option value="2">Joueur</option>
<option value="3">Joueuse</option>
</select>
</td>
</tr>
And this is working fine.
Thanks everybody ;)
From the "View" menu, select "Workspaces". You'll see all of the workspaces you've created. Select the workspaces you want to delete and click "Edit" -> "Delete Workspace", or right-click and select "Delete Workspace". If the workspace is "locked" to prevent changes, you'll get an error message.
To unlock the workspace, click "Edit" (or right-click and click "Edit Workspace") to pull up the workspace editor, uncheck the "locked" checkbox, and save your changes. You can delete the workspace once it's unlocked.
In my experience, the workspace will continue to be shown in the drop-down list until you click on it, at which point p4v will figure out you've deleted it and remove it from the list.
Check this key for 32 bits and 64 bits Windows machines.
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
and this for Windows 64 bits with 32 Bits JRE.
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment
This will work for the oracle-sun JRE.
Browser > Inspect > Element >
<.app-root _nghost-hey-c0="" ng-version="8.2.11">
In terminal
:> ng version
:> ng --version
:> ng -v
Solved, at least at the point of the question.
I searched in the web before asking, an there were no conclusive solution, the reason why this error is: lib1.so and lib2.so are not OK, very probably where not compiled for a 64 PC, but for a 32 bits machine otherwise lib3.so is a 64 bits lib. At least that is my hipothesis.
VERY unfortunately ldconfig doesn't give a clean error message informing that it could not load the library, it only pumps:
ldconfig: /folder_where_the_wicked_lib_is/ is not a symbolic link
I solved this when I removed the libs not found by ldd over the binary. Now it's easier that I know where lies the problem.
My ld version: GNU ld version 2.20.51, and I don't know if a most recent version has a better message for its users.
Thanks.
I know this is not the solution to OPs post. However, this post is the first one indexed by Google when I searched for answers to this error. For this reason I feel this will benefit others.
The following error...
The POST method is not supported for this route. Supported methods: GET, HEAD.
was caused by not clearing the routing cache
php artisan route:cache
Running the command prompt or Powershell ISE as an administrator fixed this for me.
Try the following syntax:
document.body.innerHTML += "<p>My new content</p>";
Your code is doing a log
of a number that is less than or equal to zero. That's mathematically undefined, so Python's log
function raises an exception. Here's an example:
>>> from math import log
>>> log(-1)
Traceback (most recent call last):
File "<pyshell#59>", line 1, in <module>
log(-1)
ValueError: math domain error
Without knowing what your newtonRaphson2
function does, I'm not sure I can guess where the invalid x[2]
value is coming from, but hopefully this will lead you on the right track.
An abstract class is a class that is declared abstract — it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.
In other words, a class that is declared with abstract keyword, is known as abstract class in java. It can have abstract(method without body) and non-abstract methods (method with body).
Important Note:- Abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java's approach to run-time Polymorphism is implemented through the use of superclass references. Thus, it must be possible to create a reference to an abstract class so that it can be used to point to a subclass object. You will see this feature in the below example
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){
System.out.println("running safely..");
}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
I know this is an old post, but the current answers dont address the fact that outlook and many other email providers dont support inline images or CID images. The most effective way to place images in emails is to host it online and place a link to it in the email. For small email lists a public dropbox works fine. This also keeps the email size down.
As Gregg Lind suggested, you can use reword to be prompted to only change the commit message (and leave the commit intact otherwise):
git rebase -i HEAD~n
Here, n
is the list of last n commits.
For example, if you use git rebase -i HEAD~4
, you may see something like this:
pick e459d80 Do xyz
pick 0459045 Do something
pick 90fdeab Do something else
pick facecaf Do abc
Now replace pick with reword for the commits you want to edit the messages of:
pick e459d80 Do xyz
reword 0459045 Do something
reword 90fdeab Do something else
pick facecaf Do abc
Exit the editor after saving the file, and next you will be prompted to edit the messages for the commits you had marked reword, in one file per message. Note that it would've been much simpler to just edit the commit messages when you replaced pick
with reword
, but doing that has no effect.
Learn more on GitHub's page for Changing a commit message.
To get the path of file in application package;
ContextWrapper c = new ContextWrapper(this);
Toast.makeText(this, c.getFilesDir().getPath(), Toast.LENGTH_LONG).show();
In order to have completely custom facebook login button without using com.facebook.widget.LoginButton
.
According to facebook sdk 4.x,
There new concept of login as from facebook
LoginManager and AccessToken - These new classes perform Facebook Login
So, Now you can access Facebook authentication without Facebook login button as
layout.xml
<Button
android:id="@+id/btn_fb_login"
.../>
MainActivity.java
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this.getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d("Success", "Login");
}
@Override
public void onCancel() {
Toast.makeText(MainActivity.this, "Login Cancel", Toast.LENGTH_LONG).show();
}
@Override
public void onError(FacebookException exception) {
Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
}
});
setContentView(R.layout.activity_main);
Button btn_fb_login = (Button)findViewById(R.id.btn_fb_login);
btn_fb_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile", "user_friends"));
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
For a typical example of employees owning one or more phones, see this wikibook section.
For your specific example, if you want to do a one-to-one
relationship, you should change the next code in ReleaseDateType model:
@Column(nullable = true)
private Integer media_Id;
for:
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name="CACHE_MEDIA_ID", nullable=true)
private CacheMedia cacheMedia ;
and in CacheMedia model you need to add:
@OneToOne(cascade=ALL, mappedBy="ReleaseDateType")
private ReleaseDateType releaseDateType;
then in your repository you should replace:
@Query("Select * from A a left join B b on a.id=b.id")
public List<ReleaseDateType> FindAllWithDescriptionQuery();
by:
//In this case a query annotation is not need since spring constructs the query from the method name
public List<ReleaseDateType> findByCacheMedia_Id(Integer id);
or by:
@Query("FROM ReleaseDateType AS rdt WHERE cm.rdt.cacheMedia.id = ?1") //This is using a named query method
public List<ReleaseDateType> FindAllWithDescriptionQuery(Integer id);
Or if you prefer to do a @OneToMany
and @ManyToOne
relation, you should change the next code in ReleaseDateType model:
@Column(nullable = true)
private Integer media_Id;
for:
@OneToMany(cascade=ALL, mappedBy="ReleaseDateType")
private List<CacheMedia> cacheMedias ;
and in CacheMedia model you need to add:
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="RELEASE_DATE_TYPE_ID", nullable=true)
private ReleaseDateType releaseDateType;
then in your repository you should replace:
@Query("Select * from A a left join B b on a.id=b.id")
public List<ReleaseDateType> FindAllWithDescriptionQuery();
by:
//In this case a query annotation is not need since spring constructs the query from the method name
public List<ReleaseDateType> findByCacheMedias_Id(Integer id);
or by:
@Query("FROM ReleaseDateType AS rdt LEFT JOIN rdt.cacheMedias AS cm WHERE cm.id = ?1") //This is using a named query method
public List<ReleaseDateType> FindAllWithDescriptionQuery(Integer id);
While its not bad practice to use break and there are many excellent uses for it, it should not be all you rely upon. Almost any use of a break can be written into the loop condition. Code is far more readable when real conditions are used, but in the case of a long-running or infinite loop, breaks make perfect sense. They also make sense when searching for data, as shown above.
You are trying to join Person_Fear.PersonID
onto Person_Fear.FearID
- This doesn't really make sense. You probably want something like:
SELECT Persons.Name, Persons.SS, Fears.Fear FROM Persons
LEFT JOIN Person_Fear
INNER JOIN Fears
ON Person_Fear.FearID = Fears.FearID
ON Person_Fear.PersonID = Persons.PersonID
This joins Persons
onto Fears
via the intermediate table Person_Fear
. Because the join between Persons
and Person_Fear
is a LEFT JOIN
, you will get all Persons
records.
Alternatively:
SELECT Persons.Name, Persons.SS, Fears.Fear FROM Persons
LEFT JOIN Person_Fear ON Person_Fear.PersonID = Persons.PersonID
LEFT JOIN Fears ON Person_Fear.FearID = Fears.FearID
This:
string clean = Regex.Replace(dirty, "[^a-zA-Z0-9\x20]", String.Empty);
\x20 is ascii hex for 'space' character
you can add more individual characters that you want to be allowed. If you want for example "?" to be ok in the return string add \x3f.
you have to float
your image container as follows:
HTML
<div id="container">
<div id="floated">...some other random text</div>
...
some random text
...
</div>
CSS
#container{
width: 400px;
background: yellow;
}
#floated{
float: left;
width: 150px;
background: red;
}
FIDDLE
For Kali, you must use this code after the update.
$sudo python3 get-pip.py
or if you write this, it also works but not supported anymore. So don't use:
$sudo python get-pip.py
In a project I worked at we solved this problem by implement something we called 'Batch' requests. We defined a path /batch
where we accepted json in the following format:
[
{
path: '/docs',
method: 'post',
body: {
doc_number: 1,
binder: 1
}
},
{
path: '/docs',
method: 'post',
body: {
doc_number: 5,
binder: 8
}
},
{
path: '/docs',
method: 'post',
body: {
doc_number: 6,
binder: 3
}
},
]
The response have the status code 207 (Multi-Status) and looks like this:
[
{
path: '/docs',
method: 'post',
body: {
doc_number: 1,
binder: 1
}
status: 200
},
{
path: '/docs',
method: 'post',
body: {
error: {
msg: 'A document with doc_number 5 already exists'
...
}
},
status: 409
},
{
path: '/docs',
method: 'post',
body: {
doc_number: 6,
binder: 3
},
status: 200
},
]
You could also add support for headers in this structure. We implemented something that proved useful which was variables to use between requests in a batch, meaning we can use the response from one request as input to another.
Facebook and Google have similar implementations:
https://developers.google.com/gmail/api/guides/batch
https://developers.facebook.com/docs/graph-api/making-multiple-requests
When you want to create or update a resource with the same call I would use either POST or PUT depending on the case. If the document already exist, do you want the entire document to be:
In case you want the behavior from alternative 1 you should use a POST and in case you want the behavior from alternative 2 you should use PUT.
http://restcookbook.com/HTTP%20Methods/put-vs-post/
As people already suggested you could also go for PATCH, but I prefer to keep API's simple and not use extra verbs if they are not needed.
You can also do
subset(df, aged <= laclen)
from jQuery v1.6 use prop
to check that is checkd or not
$('input:radio').prop('checked') // will return true or false
and to make it checkd use
$("input").prop("checked", true);
The behaviour of this command as been modified so you don't have to pass the -i
option:
[10:19:05] coil@coil:~/workspace/api$ composer show -i
You are using the deprecated option "installed".
Only installed packages are shown by default now.
The --all option can be used to show all packages.
Alt+# comments out the current line. It will be available in history if needed.
Surround your inline text with {{ }}
.
Caveats:
}}
{{ }}
to fix it. Just retype it or paste without formatting (Cmd ⌘+Shift+V on Mac) then add {{ }}
and hit space.{{ }}
to existing text later, it can not be surrounded by other characters, e.g. if you want parenthesis around your preformatted text, you cannot fix (my text)
by adding braces ({{my text}})
. First add space around your text ( my text )
then add the {{ }}
.Operator +
is a unary operator which converts value to number. Below I prepared a table with corresponding results of using this operator for different values.
+-----------------------------+-----------+
| Value | + (Value) |
+-----------------------------+-----------+
| 1 | 1 |
| '-1' | -1 |
| '3.14' | 3.14 |
| '3' | 3 |
| '0xAA' | 170 |
| true | 1 |
| false | 0 |
| null | 0 |
| 'Infinity' | Infinity |
| 'infinity' | NaN |
| '10a' | NaN |
| undefined | Nan |
| ['Apple'] | Nan |
| function(val){ return val } | NaN |
+-----------------------------+-----------+
Operator +
returns value for objects which have implemented method valueOf
.
let something = {
valueOf: function () {
return 25;
}
};
console.log(+something);
If 2 decimal places is your level of precision, then a "smallint" would handle this in the smallest space (2-bytes). You store the percent multiplied by 100.
EDIT: The decimal type is probably a better match. Then you don't need to manually scale. It takes 5 bytes per value.
In my case, the AllowHtml attribute was not working when combined with the OutputCache action filter. This answer solved the problem for me. Hope this helps someone.
Check this out http://www.techumber.com/2015/04/html-to-pdf-conversion-using-javascript.html
Basically you need to use html2canvas and jspdf to make it work. First you will convert your dom to image and then you will use jspdf to create pdf with the images.
EDIT: A short note on how it work. We will use two libraries to make this job done. http://html2canvas.hertzen.com/ and https://github.com/MrRio/jsPDF First we will create a dom image by using html2canvas them we will use jspdf addImage method to add that image to pdf. It seems simple but there are few bugs in jsPdf and html2cavas so you may need to change dom style temporarily. Hope this helps.
Assuming you are generating a shared library, most probably what happens is that the variant of liblog4cplus.a
you are using wasn't compiled with -fPIC
. In linux, you can confirm this by extracting the object files from the static library and checking their relocations:
ar -x liblog4cplus.a
readelf --relocs fileappender.o | egrep '(GOT|PLT|JU?MP_SLOT)'
If the output is empty, then the static library is not position-independent and cannot be used to generate a shared object.
Since the static library contains object code which was already compiled, providing the -fPIC flag won't help.
You need to get ahold of a version of liblog4cplus.a
compiled with -fPIC
and use that one instead.
** Update ** A scalars converter has been added to retrofit that allows for a String
response with less ceremony than my original answer below.
Example interface --
public interface GitHubService {
@GET("/users/{user}")
Call<String> listRepos(@Path("user") String user);
}
Add the ScalarsConverterFactory
to your retrofit builder. Note: If using ScalarsConverterFactory
and another factory, add the scalars factory first.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
// add other factories here, if needed.
.build();
You will also need to include the scalars converter in your gradle file --
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
--- Original Answer (still works, just more code) ---
I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject
land. I suspect your specific problem might be better solved using a custom gson TypeAdapter
or a retrofit Converter
if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -
First, if you are using Retrofit 2, you should start using the Call
API. Instead of sending an object to convert as the type parameter, use ResponseBody
from okhttp --
public interface GitHubService {
@GET("/users/{user}")
Call<ResponseBody> listRepos(@Path("user") String user);
}
then you can create and execute your call --
GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});
Note The code above calls string()
on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream()
instead. See the ResponseBody
docs.
@OP, for both your questions you can use case/esac:
string="node001"
case "$string" in
node*) echo "found";;
* ) echo "no node";;
esac
Second question
case "$HOST" in
node*) echo "ok";;
user) echo "ok";;
esac
case "$HOST" in
node*|user) echo "ok";;
esac
Or Bash 4.0
case "$HOST" in
user) ;&
node*) echo "ok";;
esac
You could get a JavaScript object containing the parameters with something like this:
var regex = /[?&]([^=#]+)=([^&#]*)/g,
url = window.location.href,
params = {},
match;
while(match = regex.exec(url)) {
params[match[1]] = match[2];
}
The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by =
characters, and pairs themselves separated by &
characters (or an =
character for the first one). For your example, the above would result in:
{v: "123", p: "hello"}
Here's a working example.
Use
git cherry-pick <commit-hash>
So this will pick your behind commit to git location you are on.
if you do not have any database in your application simply disable the auto-config of datasource by adding below annotation.
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
And yet another possibility:
In [2]: a = array([1, 2, 3, -4, 5])
In [3]: where(a<0, 0, a)
Out[3]: array([1, 2, 3, 0, 5])
Select your range from cell A (or the whole columns by first selecting column A). Make sure that the 'lighter coloured' cell is A1 then go to conditional formatting, new rule:
Put the following formula and the choice of your formatting (notice that the 'lighter coloured' cell comes into play here, because it is being used in the formula):
=$A1<>$B1
Then press OK and that should do it.
Here is what I ended up with for the similar problem. The idea is the same as in @Avi's answer, but I also wanted to avoid the static "System.setProperty("https.protocols", "TLSv1");", so that any adjustments won't affect the system. Inspired by an answer from here http://www.coderanch.com/t/637177/Security/Disabling-handshake-message-Java
public class MyCustomClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
try {
if (!(connection instanceof HttpsURLConnection)) {
throw new RuntimeException("An instance of HttpsURLConnection is expected");
}
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
httpsConnection.setSSLSocketFactory(new MyCustomSSLSocketFactory(sslContext.getSocketFactory()));
httpsConnection.setHostnameVerifier((hostname, session) -> true);
super.prepareConnection(httpsConnection, httpMethod);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
/**
* We need to invoke sslSocket.setEnabledProtocols(new String[] {"SSLv3"});
* see http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html (Java 8 section)
*/
private static class MyCustomSSLSocketFactory extends SSLSocketFactory {
private final SSLSocketFactory delegate;
public MyCustomSSLSocketFactory(SSLSocketFactory delegate) {
this.delegate = delegate;
}
@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
@Override
public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose) throws IOException {
final Socket underlyingSocket = delegate.createSocket(socket, host, port, autoClose);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final String host, final int port) throws IOException {
final Socket underlyingSocket = delegate.createSocket(host, port);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort) throws IOException {
final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final InetAddress host, final int port) throws IOException {
final Socket underlyingSocket = delegate.createSocket(host, port);
return overrideProtocol(underlyingSocket);
}
@Override
public Socket createSocket(final InetAddress host, final int port, final InetAddress localAddress, final int localPort) throws IOException {
final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
return overrideProtocol(underlyingSocket);
}
private Socket overrideProtocol(final Socket socket) {
if (!(socket instanceof SSLSocket)) {
throw new RuntimeException("An instance of SSLSocket is expected");
}
((SSLSocket) socket).setEnabledProtocols(new String[] {"SSLv3"});
return socket;
}
}
}
Basic syntax is: $(selector).action()
A dollar sign to define jQuery A (selector) to "query (or find)" HTML elements A jQuery action() to be performed on the element(s)
If you can't use the delay
method as Robert Harvey suggested, you can use setTimeout
.
Eg.
setTimeout(function() {$("#test").animate({"top":"-=80px"})} , 1500); // delays 1.5 sec
setTimeout(function() {$("#test").animate({"opacity":"0"})} , 1500 + 1000); // delays 1 sec after the previous one
You might also want to look at the gmpy module. It is an interface between Python and the GMP multiple-precision library. gmpy provides an invert function that does exactly what you need:
>>> import gmpy
>>> gmpy.invert(1234567, 1000000007)
mpz(989145189)
Updated answer
As noted by @hyh , the gmpy.invert()
returns 0 if the inverse does not exist. That matches the behavior of GMP's mpz_invert()
function. gmpy.divm(a, b, m)
provides a general solution to a=bx (mod m)
.
>>> gmpy.divm(1, 1234567, 1000000007)
mpz(989145189)
>>> gmpy.divm(1, 0, 5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: not invertible
>>> gmpy.divm(1, 4, 8)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: not invertible
>>> gmpy.divm(1, 4, 9)
mpz(7)
divm()
will return a solution when gcd(b,m) == 1
and raises an exception when the multiplicative inverse does not exist.
Disclaimer: I'm the current maintainer of the gmpy library.
Updated answer 2
gmpy2 now properly raises an exception when the inverse does not exists:
>>> import gmpy2
>>> gmpy2.invert(0,5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: invert() no inverse exists
The following code returns dataframe with the 'Category' column replaced by categorical columns:
df_with_dummies = pd.get_dummies(df, prefix='Category_', columns=['Category'])
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html
To convert the byte[] to string[], simply use the below line.
byte[] fileData; // Some byte array
//Convert byte[] to string[]
var table = (Encoding.Default.GetString(
fileData,
0,
fileData.Length - 1)).Split(new string[] { "\r\n", "\r", "\n" },
StringSplitOptions.None);
i would go around this by making a 2d dynamic array:
long long** a = new long long*[x];
for (unsigned i = 0; i < x; i++) a[i] = new long long[y];
more on this here https://stackoverflow.com/a/936702/3517001
How to create an array size 5 containing pointers to characters:
char *array_of_pointers[ 5 ]; //array size 5 containing pointers to char
char m = 'm'; //character value holding the value 'm'
array_of_pointers[0] = &m; //assign m ptr into the array position 0.
printf("%c", *array_of_pointers[0]); //get the value of the pointer to m
How to create a pointer to an array of characters:
char (*pointer_to_array)[ 5 ]; //A pointer to an array containing 5 chars
char m = 'm'; //character value holding the value 'm'
*pointer_to_array[0] = m; //dereference array and put m in position 0
printf("%c", (*pointer_to_array)[0]); //dereference array and get position 0
How to create an 2D array containing pointers to characters:
char *array_of_pointers[5][2];
//An array size 5 containing arrays size 2 containing pointers to char
char m = 'm';
//character value holding the value 'm'
array_of_pointers[4][1] = &m;
//Get position 4 of array, then get position 1, then put m ptr in there.
printf("%c", *array_of_pointers[4][1]);
//Get position 4 of array, then get position 1 and dereference it.
How to create a pointer to an 2D array of characters:
char (*pointer_to_array)[5][2];
//A pointer to an array size 5 each containing arrays size 2 which hold chars
char m = 'm';
//character value holding the value 'm'
(*pointer_to_array)[4][1] = m;
//dereference array, Get position 4, get position 1, put m there.
printf("%c", (*pointer_to_array)[4][1]);
//dereference array, Get position 4, get position 1
To help you out with understanding how humans should read complex C/C++ declarations read this: http://www.programmerinterview.com/index.php/c-cplusplus/c-declarations/
The problem I need to solve is to store contracts containing a few fields (address, book, num_of_days, borrower_addr, blk_data), blk_data is a transaction list (block number and transaction address). This question and answer helped me. I would like to share my code as below. Hope this helps.
- Schema definition. See blk_data.
var ContractSchema = new Schema(
{
address: {type: String, required: true, max: 100}, //contract address
// book_id: {type: String, required: true, max: 100}, //book id in the book collection
book: { type: Schema.ObjectId, ref: 'clc_books', required: true }, // Reference to the associated book.
num_of_days: {type: Number, required: true, min: 1},
borrower_addr: {type: String, required: true, max: 100},
// status: {type: String, enum: ['available', 'Created', 'Locked', 'Inactive'], default:'Created'},
blk_data: [{
tx_addr: {type: String, max: 100}, // to do: change to a list
block_number: {type: String, max: 100}, // to do: change to a list
}]
}
);
- Create a record for the collection in the MongoDB. See blk_data.
// Post submit a smart contract proposal to borrowing a specific book.
exports.ctr_contract_propose_post = [
// Validate fields
body('book_id', 'book_id must not be empty.').isLength({ min: 1 }).trim(),
body('req_addr', 'req_addr must not be empty.').isLength({ min: 1 }).trim(),
body('new_contract_addr', 'contract_addr must not be empty.').isLength({ min: 1 }).trim(),
body('tx_addr', 'tx_addr must not be empty.').isLength({ min: 1 }).trim(),
body('block_number', 'block_number must not be empty.').isLength({ min: 1 }).trim(),
body('num_of_days', 'num_of_days must not be empty.').isLength({ min: 1 }).trim(),
// Sanitize fields.
sanitizeBody('*').escape(),
// Process request after validation and sanitization.
(req, res, next) => {
// Extract the validation errors from a request.
const errors = validationResult(req);
if (!errors.isEmpty()) {
// There are errors. Render form again with sanitized values/error messages.
res.status(400).send({ errors: errors.array() });
return;
}
// Create a Book object with escaped/trimmed data and old id.
var book_fields =
{
_id: req.body.book_id, // This is required, or a new ID will be assigned!
cur_contract: req.body.new_contract_addr,
status: 'await_approval'
};
async.parallel({
//call the function get book model
books: function(callback) {
Book.findByIdAndUpdate(req.body.book_id, book_fields, {}).exec(callback);
},
}, function(error, results) {
if (error) {
res.status(400).send({ errors: errors.array() });
return;
}
if (results.books.isNew) {
// res.render('pg_error', {
// title: 'Proposing a smart contract to borrow the book',
// c: errors.array()
// });
res.status(400).send({ errors: errors.array() });
return;
}
var contract = new Contract(
{
address: req.body.new_contract_addr,
book: req.body.book_id,
num_of_days: req.body.num_of_days,
borrower_addr: req.body.req_addr
});
var blk_data = {
tx_addr: req.body.tx_addr,
block_number: req.body.block_number
};
contract.blk_data.push(blk_data);
// Data from form is valid. Save book.
contract.save(function (err) {
if (err) { return next(err); }
// Successful - redirect to new book record.
resObj = {
"res": contract.url
};
res.status(200).send(JSON.stringify(resObj));
// res.redirect();
});
});
},
];
- Update a record. See blk_data.
// Post lender accept borrow proposal.
exports.ctr_contract_propose_accept_post = [
// Validate fields
body('book_id', 'book_id must not be empty.').isLength({ min: 1 }).trim(),
body('contract_id', 'book_id must not be empty.').isLength({ min: 1 }).trim(),
body('tx_addr', 'tx_addr must not be empty.').isLength({ min: 1 }).trim(),
body('block_number', 'block_number must not be empty.').isLength({ min: 1 }).trim(),
// Sanitize fields.
sanitizeBody('*').escape(),
// Process request after validation and sanitization.
(req, res, next) => {
// Extract the validation errors from a request.
const errors = validationResult(req);
if (!errors.isEmpty()) {
// There are errors. Render form again with sanitized values/error messages.
res.status(400).send({ errors: errors.array() });
return;
}
// Create a Book object with escaped/trimmed data
var book_fields =
{
_id: req.body.book_id, // This is required, or a new ID will be assigned!
status: 'on_loan'
};
// Create a contract object with escaped/trimmed data
var contract_fields = {
$push: {
blk_data: {
tx_addr: req.body.tx_addr,
block_number: req.body.block_number
}
}
};
async.parallel({
//call the function get book model
book: function(callback) {
Book.findByIdAndUpdate(req.body.book_id, book_fields, {}).exec(callback);
},
contract: function(callback) {
Contract.findByIdAndUpdate(req.body.contract_id, contract_fields, {}).exec(callback);
},
}, function(error, results) {
if (error) {
res.status(400).send({ errors: errors.array() });
return;
}
if ((results.book.isNew) || (results.contract.isNew)) {
res.status(400).send({ errors: errors.array() });
return;
}
var resObj = {
"res": results.contract.url
};
res.status(200).send(JSON.stringify(resObj));
});
},
];
SELECT
A.P_NAME AS [INDIVIDUAL NAME],B.F_DETAIL AS [INDIVIDUAL FEATURE],C.PL_PLACE AS [INDIVIDUAL LOCATION]
FROM
[dbo].[PEOPLE] A
INNER JOIN
[dbo].[FEATURE] B ON A.P_FEATURE = B.F_ID
INNER JOIN
[dbo].[PEOPLE_LOCATION] C ON A.P_LOCATION = C.PL_ID
Using a regex approach:
$regex = <<<'END'
/
(
(?: [\x00-\x7F] # single-byte sequences 0xxxxxxx
| [\xC0-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
| [\xE0-\xEF][\x80-\xBF]{2} # triple-byte sequences 1110xxxx 10xxxxxx * 2
| [\xF0-\xF7][\x80-\xBF]{3} # quadruple-byte sequence 11110xxx 10xxxxxx * 3
){1,100} # ...one or more times
)
| . # anything else
/x
END;
preg_replace($regex, '$1', $text);
It searches for UTF-8 sequences, and captures those into group 1. It also matches single bytes that could not be identified as part of a UTF-8 sequence, but does not capture those. Replacement is whatever was captured into group 1. This effectively removes all invalid bytes.
It is possible to repair the string, by encoding the invalid bytes as UTF-8 characters. But if the errors are random, this could leave some strange symbols.
$regex = <<<'END'
/
(
(?: [\x00-\x7F] # single-byte sequences 0xxxxxxx
| [\xC0-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
| [\xE0-\xEF][\x80-\xBF]{2} # triple-byte sequences 1110xxxx 10xxxxxx * 2
| [\xF0-\xF7][\x80-\xBF]{3} # quadruple-byte sequence 11110xxx 10xxxxxx * 3
){1,100} # ...one or more times
)
| ( [\x80-\xBF] ) # invalid byte in range 10000000 - 10111111
| ( [\xC0-\xFF] ) # invalid byte in range 11000000 - 11111111
/x
END;
function utf8replacer($captures) {
if ($captures[1] != "") {
// Valid byte sequence. Return unmodified.
return $captures[1];
}
elseif ($captures[2] != "") {
// Invalid byte of the form 10xxxxxx.
// Encode as 11000010 10xxxxxx.
return "\xC2".$captures[2];
}
else {
// Invalid byte of the form 11xxxxxx.
// Encode as 11000011 10xxxxxx.
return "\xC3".chr(ord($captures[3])-64);
}
}
preg_replace_callback($regex, "utf8replacer", $text);
EDIT:
!empty(x)
will match non-empty values ("0"
is considered empty).x != ""
will match non-empty values, including "0"
.x !== ""
will match anything except ""
.x != ""
seem the best one to use in this case.
I have also sped up the match a little. Instead of matching each character separately, it matches sequences of valid UTF-8 characters.
Trick question, unless it's been quoted improperly. Just read through the file once to get the maximum integer n
, and return n+1
.
Of course you'd need a backup plan in case n+1
causes an integer overflow.
You can also use:
@if(string.IsNullOrEmpty(Model.CreatorFullName))
{
...your code...
}
No need for a variable in the code
Here is the code you need to ensure that only one instance is running. This is the method of using a named mutex.
public class Program
{
static System.Threading.Mutex singleton = new Mutex(true, "My App Name");
static void Main(string[] args)
{
if (!singleton.WaitOne(TimeSpan.Zero, true))
{
//there is already another instance running!
Application.Exit();
}
}
}
The nearest equivalents would be icode and bcode as used by scalac, view Miguel Garcia's site on the Scalac optimiser for more information, here: http://magarciaepfl.github.io/scala/
You might also consider Java bytecode itself to be your intermediate representation, given that bytecode is the ultimate output of scalac.
Or perhaps the true intermediate is something that the JIT produces before it finally outputs native instructions?
Ultimately though... There's no single place that you can point at an claim "there's the intermediate!". Scalac works in phases that successively change the abstract syntax tree, every single phase produces a new intermediate. The whole thing is like an onion, and it's very hard to try and pick out one layer as somehow being more significant than any other.
Normally the views belong with a specific matching controller that supports its data requirements, or the view belongs in the Views/Shared
folder if shared between controllers (hence the name).
You can refer to views/partial views from another controller, by specifying the full path (including extension) like:
return PartialView("~/views/ABC/XXX.cshtml", zyxmodel);
or a relative path (no extension), based on the answer by @Max Toro
return PartialView("../ABC/XXX", zyxmodel);
BUT THIS IS NOT A GOOD IDEA ANYWAY
*Note: These are the only two syntax that work. not ABC\\XXX
or ABC/XXX
or any other variation as those are all relative paths and do not find a match.
You can use Html.Renderpartial
in your view instead, but it requires the extension as well:
Html.RenderPartial("~/Views/ControllerName/ViewName.cshtml", modeldata);
Use @Html.Partial
for inline Razor syntax:
@Html.Partial("~/Views/ControllerName/ViewName.cshtml", modeldata)
You can use the ../controller/view
syntax with no extension (again credit to @Max Toro):
@Html.Partial("../ControllerName/ViewName", modeldata)
Note: Apparently RenderPartial
is slightly faster than Partial, but that is not important.
If you want to actually call the other controller, use:
@Html.Action("action", "controller", parameters)
My personal preference is to use @Html.Action
as it allows each controller to manage its own views, rather than cross-referencing views from other controllers (which leads to a large spaghetti-like mess).
You would normally pass just the required key values (like any other view) e.g. for your example:
@Html.Action("XXX", "ABC", new {id = model.xyzId })
This will execute the ABC.XXX
action and render the result in-place. This allows the views and controllers to remain separately self-contained (i.e. reusable).
I have just hit a situation where I could not use @Html.Action, but needed to create a view path based on a action
and controller
names. To that end I added this simple View
extension method to UrlHelper
so you can say return PartialView(Url.View("actionName", "controllerName"), modelData)
:
public static class UrlHelperExtension
{
/// <summary>
/// Return a view path based on an action name and controller name
/// </summary>
/// <param name="url">Context for extension method</param>
/// <param name="action">Action name</param>
/// <param name="controller">Controller name</param>
/// <returns>A string in the form "~/views/{controller}/{action}.cshtml</returns>
public static string View(this UrlHelper url, string action, string controller)
{
return string.Format("~/Views/{1}/{0}.cshtml", action, controller);
}
}
I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between
BEGIN
SELECT MONTH(CURDATE()) INTO @curmonth;
SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
SELECT DAY(@checkweekday) INTO @checkday;
SET @daycount = 0;
SET @workdays = 0;
WHILE(@daycount < @totaldays) DO
IF (WEEKDAY(@checkweekday) < 5) THEN
SET @workdays = @workdays+1;
END IF;
SET @daycount = @daycount+1;
SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
END WHILE;
END
Just for others:
If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query
delimiter ;;
drop procedure if exists test2;;
create procedure test2()
begin
select ‘Hello World’;
end
;;
Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.
The first_day function you need is: How to get first day of every corresponding month in mysql?
Showing the Procedure is working Simply add the following line below END WHILE and above END
SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;
Then use the following code in the SQL Query Window.
call test2 /* or whatever you changed the name of the stored procedure to */
NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).
To resolve the issues make sure you are using build tools version "23.0.0 rc2" with the following tools build gradle dependency:
classpath 'com.android.tools.build:gradle:1.3.0-beta2'
Handy one liner to parse a CSV file into an array
$csv = array_map('str_getcsv', file('data.csv'));
Try calling it like: obj.some_function( '1', 2, '3', g="foo", h="bar" )
. After the required positional arguments, you can specify specific optional arguments by name.
If you have an older version of memcached and need a script to wrap memcached as a service, here it is: Memcached Service Script
If you use Bootstrap, try to assign margin-bottom 0 to the paragraph and after assign the property align-items-center to container, for example, like this:
<div class="row align-items-center">
<p class="col-sm-1 mb-0">
....
</p>
</div>
Bootstrap by default assign a calculate margin bottom, so mb-0 disabled this.
I hope it helps
You can use the find
function, found in the std
namespace, ie std::find
. You pass the std::find
function the begin
and end
iterator from the vector you want to search, along with the element you're looking for and compare the resulting iterator to the end of the vector to see if they match or not.
std::find(vector.begin(), vector.end(), item) != vector.end()
You're also able to dereference that iterator and use it as normal, like any other iterator.
Here is a snippet I used within a Presenter filling a view with a Nullable Date/Time
memDateLogin = m.memDateLogin ?? DateTime.MinValue
Use the logging module
def init_logging():
rootLogger = logging.getLogger('my_logger')
LOG_DIR = os.getcwd() + '/' + 'logs'
if not os.path.exists(LOG_DIR):
os.makedirs(LOG_DIR)
fileHandler = logging.FileHandler("{0}/{1}.log".format(LOG_DIR, "g2"))
rootLogger.addHandler(fileHandler)
rootLogger.setLevel(logging.DEBUG)
consoleHandler = logging.StreamHandler()
rootLogger.addHandler(consoleHandler)
return rootLogger
Get the logger:
logger = init_logging()
And start logging/output(ing):
logger.debug('Hi! :)')
I had this, I added EXIT
and initially it didn't work, I guess per requiring the called program exiting
advice mentioned in another response here, however it now works without further ado - not sure what's caused this, but the point to note is that I'm calling a data file .html
rather than the program that handles it browser.exe
, I did not edit anything else but suffice it to say it's much neater just using a bat file to access the main access pages of those web documents and only having title.bat
, contents.bat
, index.bat
in the root folder with the rest of the content in a subfolder.
i.e.: contents.bat reads
cd subfolder
"contents.html"
exit
It also looks better if I change the bat file icons for just those items to suit the context they are in too, but that's another matter, hiding the bat files in the subfolder and creating custom icon shortcuts to them in the root folder with the images called for the customisation also hidden.
It must be at least 64 bits. Other than that it's implementation defined.
Strictly speaking, unsigned long long
isn't standard in C++ until the C++0x standard. unsigned long long
is a 'simple-type-specifier' for the type unsigned long long int
(so they're synonyms).
The long long
set of types is also in C99 and was a common extension to C++ compilers even before being standardized.
Try adding/editing lower_case_table_names = 2 in my.ini
or my.cnf
you're getting that poor transition because you're adjusting the position of the element every time the document is scrolled. What you want is to use fixed positioning. I tried that fixed center plugin listed above and that seems to do solve the problem nicely. Fixed positioning allows you to center an element once, and the CSS property will take care of maintaining that position for you every time you scroll.
try {
File img = new File("somefile.png");
BufferedImage image = ImageIO.read(img );
System.out.println(image);
} catch (IOException e) {
e.printStackTrace();
}
Example output for my image file:
BufferedImage@5d391d: type = 5 ColorModel: #pixelBits = 24
numComponents = 3 color
space = java.awt.color.ICC_ColorSpace@50a649
transparency = 1
has alpha = false
isAlphaPre = false
ByteInterleavedRaster:
width = 800
height = 600
#numDataElements 3
dataOff[0] = 2
You can run System.out.println(object); on just about any object and get some information about it.
Never, never, never say
if something == True:
Never. It's crazy, since you're redundantly repeating what is redundantly specified as the redundant condition rule for an if-statement.
Worse, still, never, never, never say
if something == False:
You have not
. Feel free to use it.
Finally, doing a == None
is inefficient. Do a is None
. None
is a special singleton object, there can only be one. Just check to see if you have that object.
document.getElementById("fName").style.border="1px solid black";
For me the dialogue appears more than one if I click the dpFlightDate edit text more than one time same for the timmer dialog . how can I avoid this dialog to appear only once and if the user click's 2nd time the dialog must not appear again ie if dialog is on the screen ?
// perform click event on edit text
dpFlightDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// calender class's instance and get current date , month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog = new DatePickerDialog(frmFlightDetails.this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
dpFlightDate.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
tpFlightTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog
timePickerDialog = new TimePickerDialog(frmFlightDetails.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
tpFlightTime.setText( selectedHour + ":" + selectedMinute);
}
}, hour, minute, true);//Yes 24 hour time
timePickerDialog.setTitle("Select Time");
timePickerDialog.show();
}
});
So imagine everyone is trying to go to the bathroom and there's only a certain number of keys to the bathroom. Now if there's not enough keys left, that person needs to wait. So think of semaphore as representing those set of keys available for bathrooms (the system resources) that different processes (bathroom goers) can request access to.
Now imagine two processes trying to go to the bathroom at the same time. That's not a good situation and semaphores are used to prevent this. Unfortunately, the semaphore is a voluntary mechanism and processes (our bathroom goers) can ignore it (i.e. even if there are keys, someone can still just kick the door open).
There are also differences between binary/mutex & counting semaphores.
Check out the lecture notes at http://www.cs.columbia.edu/~jae/4118/lect/L05-ipc.html.
INTRODUCTION
This answer corrects the very broken but shockingly top voted answer of this thread (written by TheMarko):
#!/usr/bin/env bash
BASEDIR=$(dirname "$0")
echo "$BASEDIR"
WHY DOES USING dirname "$0" ON IT'S OWN NOT WORK?
dirname $0 will only work if user launches script in a very specific way. I was able to find several situations where this answer fails and crashes the script.
First of all, let's understand how this answer works. He's getting the script directory by doing
dirname "$0"
$0 represents the first part of the command calling the script (it's basically the inputted command without the arguments:
/some/path/./script argument1 argument2
$0="/some/path/./script"
dirname basically finds the last / in a string and truncates it there. So if you do:
dirname /usr/bin/sha256sum
you'll get: /usr/bin
This example works well because /usr/bin/sha256sum is a properly formatted path but
dirname "/some/path/./script"
wouldn't work well and would give you:
BASENAME="/some/path/." #which would crash your script if you try to use it as a path
Say you're in the same dir as your script and you launch it with this command
./script
$0 in this situation will be ./script and dirname $0 will give:
. #or BASEDIR=".", again this will crash your script
Using:
sh script
Without inputting the full path will also give a BASEDIR="."
Using relative directories:
../some/path/./script
Gives a dirname $0 of:
../some/path/.
If you're in the /some directory and you call the script in this manner (note the absence of / in the beginning, again a relative path):
path/./script.sh
You'll get this value for dirname $0:
path/.
and ./path/./script (another form of the relative path) gives:
./path/.
The only two situations where basedir $0 will work is if the user use sh or touch to launch a script because both will result in $0:
$0=/some/path/script
which will give you a path you can use with dirname.
THE SOLUTION
You'd have account for and detect every one of the above mentioned situations and apply a fix for it if it arises:
#!/bin/bash
#this script will only work in bash, make sure it's installed on your system.
#set to false to not see all the echos
debug=true
if [ "$debug" = true ]; then echo "\$0=$0";fi
#The line below detect script's parent directory. $0 is the part of the launch command that doesn't contain the arguments
BASEDIR=$(dirname "$0") #3 situations will cause dirname $0 to fail: #situation1: user launches script while in script dir ( $0=./script)
#situation2: different dir but ./ is used to launch script (ex. $0=/path_to/./script)
#situation3: different dir but relative path used to launch script
if [ "$debug" = true ]; then echo 'BASEDIR=$(dirname "$0") gives: '"$BASEDIR";fi
if [ "$BASEDIR" = "." ]; then BASEDIR="$(pwd)";fi # fix for situation1
_B2=${BASEDIR:$((${#BASEDIR}-2))}; B_=${BASEDIR::1}; B_2=${BASEDIR::2}; B_3=${BASEDIR::3} # <- bash only
if [ "$_B2" = "/." ]; then BASEDIR=${BASEDIR::$((${#BASEDIR}-1))};fi #fix for situation2 # <- bash only
if [ "$B_" != "/" ]; then #fix for situation3 #<- bash only
if [ "$B_2" = "./" ]; then
#covers ./relative_path/(./)script
if [ "$(pwd)" != "/" ]; then BASEDIR="$(pwd)/${BASEDIR:2}"; else BASEDIR="/${BASEDIR:2}";fi
else
#covers relative_path/(./)script and ../relative_path/(./)script, using ../relative_path fails if current path is a symbolic link
if [ "$(pwd)" != "/" ]; then BASEDIR="$(pwd)/$BASEDIR"; else BASEDIR="/$BASEDIR";fi
fi
fi
if [ "$debug" = true ]; then echo "fixed BASEDIR=$BASEDIR";fi
No, you can't undo, rollback or reverse a commit.
(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE
or similar, not an rm -rf /data/directory
scenario).
If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate
so that no checkpoint is run on shutdown.
You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.
If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.
Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base
, pg_clog
, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog
etc. No part is unimportant.
Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.
If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT
or UPDATE
. Thus, the old versions of the UPDATE
d rows might still be lying around, present but inaccessible.
Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter
and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl
in immediate
mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.
Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.
You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.
I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOAST
ed data so it's of limited utility. Give it a try, if you're lucky it might work.
See: pg_dirtyread on GitHub.
I've removed what I'd written in this section as it's obsoleted by that tool.
See also PostgreSQL row storage fundamentals
See my blog entry Preventing PostgreSQL database corruption.
On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED
for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.
Xcode 8.2, iOS 10
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Doing it in one bulk read:
import re
textfile = open(filename, 'r')
filetext = textfile.read()
textfile.close()
matches = re.findall("(<(\d{4,5})>)?", filetext)
Line by line:
import re
textfile = open(filename, 'r')
matches = []
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
matches += reg.findall(line)
textfile.close()
But again, the matches that returns will not be useful for anything except counting unless you added an offset counter:
import re
textfile = open(filename, 'r')
matches = []
offset = 0
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
matches += [(reg.findall(line),offset)]
offset += len(line)
textfile.close()
But it still just makes more sense to read the whole file in at once.
It's torture. Instead of including a generic conf file, they make you hit return 9000 times to generate one.
@param
won't affect the number. It's just for making javadocs.
More on javadoc: http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html
I think you may want to introduce some helper functions to build
your button as well as a Stateful widget along with some property to key off of.
isButtonDisabled
)onPressed
value to either null
or some function onPressed: () {}
isButtonDisabled
as part of this conditional and return either null
or some function.setState(() => isButtonDisabled = true)
to flip the conditional variable.build()
method again with the new state and the button will be rendered with a null
press handler and be disabled.Here's is some more context using the Flutter counter project.
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
bool _isButtonDisabled;
@override
void initState() {
_isButtonDisabled = false;
}
void _incrementCounter() {
setState(() {
_isButtonDisabled = true;
_counter++;
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("The App"),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'You have pushed the button this many times:',
),
new Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
_buildCounterButton(),
],
),
),
);
}
Widget _buildCounterButton() {
return new RaisedButton(
child: new Text(
_isButtonDisabled ? "Hold on..." : "Increment"
),
onPressed: _isButtonDisabled ? null : _incrementCounter,
);
}
}
In this example I am using an inline ternary to conditionally set the Text
and onPressed
, but it may be more appropriate for you to extract this into a function (you can use this same method to change the text of the button as well):
Widget _buildCounterButton() {
return new RaisedButton(
child: new Text(
_isButtonDisabled ? "Hold on..." : "Increment"
),
onPressed: _counterButtonPress(),
);
}
Function _counterButtonPress() {
if (_isButtonDisabled) {
return null;
} else {
return () {
// do anything else you may want to here
_incrementCounter();
};
}
}
This is answered in the documentation:
Where MySQL Stores Temporary Files
On Unix, MySQL uses the value of the TMPDIR environment variable as the path name of the directory in which to store temporary files. If TMPDIR is not set, MySQL uses the system default, which is usually /tmp, /var/tmp, or /usr/tmp.
On Windows, Netware and OS2, MySQL checks in order the values of the TMPDIR, TEMP, and TMP environment variables. For the first one found to be set, MySQL uses it and does not check those remaining. If none of TMPDIR, TEMP, or TMP are set, MySQL uses the Windows system default, which is usually C:\windows\temp.
You are putting in place an overloading when you change the original types for the arguments in the signature of a method.
You are putting in place an overriding when you change the original Implementation of a method in a derived class.
Actually you must surround it with an Try/Catch block so your code won't stop from working. Like this:
try{
if(typeof response[0].title !== 'undefined') {
doSomething();
}
}catch(e){
console.log('responde[0].title is undefined');
}
The onclick
attribute on your anchor tag is going to call a client-side function. (This is what you would use if you wanted to call a javascript function when the link is clicked.)
What you want is a server-side control, like the LinkButton
:
<asp:LinkButton ID="lnkTutorial" runat="server" Text="Tutorial" OnClick="displayTutorial_Click"/>
This has an OnClick
attribute that will call the method in your code behind.
Looking further into your code, it looks like you're just trying to open a different tutorial based on access level of the user. You don't need an event handler for this at all. A far better approach would be to just set the end point of your LinkButton
control in the code behind.
protected void Page_Load(object sender, EventArgs e)
{
userinfo = (UserInfo)Session["UserInfo"];
if (userinfo.user == "Admin")
{
lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
}
else
{
lnkTutorial.PostBackUrl = "help/UserTutorial.html";
}
}
Really, it would be best to check that you actually have a user first.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserInfo"] != null && ((UserInfo)Session["UserInfo"]).user == "Admin")
{
lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
}
else
{
lnkTutorial.PostBackUrl = "help/UserTutorial.html";
}
}
These answers are no longer recommended since try_files
works faster than if
in this context. Simply add try_files
in your php location block to test if the file exists, otherwise return a 404.
location ~ \.php {
try_files $uri =404;
...
}
In our case, the Windows service account that SQL Server and SQL Agent were running under were locked out in Active Directory.
This just a slight addition to @TomM's
answer/ A simple function to check
if your Selection's cells are empty
Public Function CheckIfSelectionIsEmpty() As Boolean
Dim emptySelection As Boolean:emptySelection=True
Dim cell As Range
For Each cell In Selection
emptySelection = emptySelection And isEmpty(cell)
If emptySelection = False Then
Exit For
End If
Next
CheckIfSelectionIsEmpty = emptySelection
End Function
You can still use the Authorization header with OAuth 2.0. There is a Bearer type specified in the Authorization header for use with OAuth bearer tokens (meaning the client app simply has to present ("bear") the token). The value of the header is the access token the client received from the Authorization Server.
It's documented in this spec: https://tools.ietf.org/html/rfc6750#section-2.1
E.g.:
GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer mF_9.B5f-4.1JqM
Where mF_9.B5f-4.1JqM is your OAuth access token.
For modifying the status I think a RESTful approach is to use a logical sub-resource which describes the status of the resources. This IMO is pretty useful and clean when you have a reduced set of statuses. It makes your API more expressive without forcing the existing operations for your customer resource.
Example:
POST /customer/active <-- Providing entity in the body a new customer
{
... // attributes here except status
}
The POST service should return the newly created customer with the id:
{
id:123,
... // the other fields here
}
The GET for the created resource would use the resource location:
GET /customer/123/active
A GET /customer/123/inactive should return 404
For the PUT operation, without providing a Json entity it will just update the status
PUT /customer/123/inactive <-- Deactivating an existing customer
Providing an entity will allow you to update the contents of the customer and update the status at the same time.
PUT /customer/123/inactive
{
... // entity fields here except id and status
}
You are creating a conceptual sub-resource for your customer resource. It is also consistent with Roy Fielding's definition of a resource: "...A resource is a conceptual mapping to a set of entities, not the entity that corresponds to the mapping at any particular point in time..." In this case the conceptual mapping is active-customer to customer with status=ACTIVE.
Read operation:
GET /customer/123/active
GET /customer/123/inactive
If you make those calls one right after the other one of them must return status 404, the successful output may not include the status as it is implicit. Of course you can still use GET /customer/123?status=ACTIVE|INACTIVE to query the customer resource directly.
The DELETE operation is interesting as the semantics can be confusing. But you have the option of not publishing that operation for this conceptual resource, or use it in accordance with your business logic.
DELETE /customer/123/active
That one can take your customer to a DELETED/DISABLED status or to the opposite status (ACTIVE/INACTIVE).
The typed way to do this would be:
Number(true) // 1
Number(false) // 0
From youMightNotNeedJquery.com + JSON.stringify
var request = new XMLHttpRequest();
request.open('POST', '/my/url', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(JSON.stringify(data));
For initial array, better use object instead of array, as then you won't be worrying about the indexes and it will be much more clear what is what:
const initialArr = [{
color: "blue",
text: "text1"
}, {
color: "red",
text: "text2"
}];
For actual mapping, use JS Array map instead of for loop - for loop should be used in cases when there's no actual array defined, like displaying something a certain number of times:
onPress = () => {
...
};
renderButtons() {
return initialArr.map((item) => {
return (
<Button
style={{ borderColor: item.color }}
onPress={this.onPress}
>
{item.text}
</Button>
);
});
}
...
render() {
return (
<View style={...}>
{
this.renderButtons()
}
</View>
)
}
I moved the mapping to separate function outside of render method for more readable code. There are many other ways to loop through list of elements in react native, and which way you'll use depends on what do you need to do. Most of these ways are covered in this article about React JSX loops, and although it's using React examples, everything from it can be used in React Native. Please check it out if you're interested in this topic!
Also, not on the topic on the looping, but as you're already using the array syntax for defining the onPress function, there's no need to bind it again. This, again, applies only if the function is defined using this syntax within the component, as the arrow syntax auto binds the function.
Add the following lines to your ~/.bash_profile
or ~/.zshrc
file(s).
export LC_CTYPE=C
export LANG=C
This will allow both positive and negative integers
ValidationExpression="^-?[0-9]\d*(\d+)?$"
Try the following:
<a asp-controller="Users" asp-action="Index"></a>
(Valid for ASP.NET 5 and MVC 6)
I have same problem after update android studio to 1.5, and i fix it by update the gradle location,
Hope this method works for you,
Frequently use this:
grep
can be used in conjunction with -r
(recursive), i
(ignore case) and -o
(prints only matching part of lines). To exclude files
use --exclude
and to exclude directories use --exclude-dir
.
Putting it together you end up with something like:
grep -rio --exclude={filenames comma separated} \
--exclude-dir={directory names comma separated} <search term> <location>
Describing it makes it sound far more complicated than it actually is. Easier to illustrate with a simple example.
Example:
Suppose I am searching for current project for all places where I explicitly set the string value debugger
during a debugging session, and now wish to review / remove.
I write a script called findDebugger.sh
and use grep
to find all occurrences. However:
For file exclusions - I wish to ensure that .eslintrc
is ignored (this actually has a linting rule about debugger
so should be excluded). Likewise, I don't want my own script to be referenced in any results.
For directory exclusions - I wish to exclude node_modules
as it contains lots of libraries that do reference debugger
and I am not interested in those results. Also I just wish to omit .idea
and .git
hidden directories because I don't care about those search locations either, and wish to keep the search performant.
So here is the result - I create a script called findDebugger.sh
with:
#!/usr/bin/env bash
grep -rio --exclude={.eslintrc,findDebugger.sh} \
--exclude-dir={node_modules,.idea,.git} debugger .
By default ls -t
sorts output from newest to oldest, so the combination of commands to use depends in which direction you want your output to be ordered.
For the newest 5 files ordered from newest to oldest, use head
to take the first 5 lines of output:
ls -t | head -n 5
For the newest 5 files ordered from oldest to newest, use the -r
switch to reverse ls
's sort order, and use tail
to take the last 5 lines of output:
ls -tr | tail -n 5
Create new Maven file with path as classpath and goal as class name
This is round robin DNS. This is a quite simple solution for load balancing. Usually DNS servers rotate/shuffle the DNS records for each incoming DNS request. Unfortunately it's not a real solution for fail-over. If one of the servers fail, some visitors will still be directed to this failed server.
For me in windows 7 it started to work only after I gave 'Read & execute', 'List folder contents', 'Read' permissions to site folder for both users
I'm using:
template <class _Ty>
inline _Ty n_Align_Up(_Ty n_x, _Ty n_alignment)
{
assert(n_alignment > 0);
//n_x += (n_x >= 0)? n_alignment - 1 : 1 - n_alignment; // causes to round away from zero (greatest absolute value)
n_x += (n_x >= 0)? n_alignment - 1 : -1; // causes to round up (towards positive infinity)
//n_x += (_Ty(-(n_x >= 0)) & n_alignment) - 1; // the same as above, avoids branch and integer multiplication
//n_x += n_alignment - 1; // only works for positive numbers (fastest)
return n_x - n_x % n_alignment; // rounds negative towards zero
}
and for powers of two:
template <class _Ty>
bool b_Is_POT(_Ty n_x)
{
return !(n_x & (n_x - 1));
}
template <class _Ty>
inline _Ty n_Align_Up_POT(_Ty n_x, _Ty n_pot_alignment)
{
assert(n_pot_alignment > 0);
assert(b_Is_POT(n_pot_alignment)); // alignment must be power of two
-- n_pot_alignment;
return (n_x + n_pot_alignment) & ~n_pot_alignment; // rounds towards positive infinity (i.e. negative towards zero)
}
Note that both of those round negative values towards zero (that means round to positive infinity for all values), neither of them relies on signed overflow (which is undefined in C/C++).
This gives:
n_Align_Up(10, 100) = 100
n_Align_Up(110, 100) = 200
n_Align_Up(0, 100) = 0
n_Align_Up(-10, 100) = 0
n_Align_Up(-110, 100) = -100
n_Align_Up(-210, 100) = -200
n_Align_Up_POT(10, 128) = 128
n_Align_Up_POT(130, 128) = 256
n_Align_Up_POT(0, 128) = 0
n_Align_Up_POT(-10, 128) = 0
n_Align_Up_POT(-130, 128) = -128
n_Align_Up_POT(-260, 128) = -256
If you mark a form element as required=""
then novalidate=""
does not help.
A way to circumvent the required
validation is to disable the element.
Quoting from Conda: Myths and Misconceptions (a comprehensive description):
...
Reality: Conda and pip serve different purposes, and only directly compete in a small subset of tasks: namely installing Python packages in isolated environments.
Pip, which stands for Pip Installs Packages, is Python's officially-sanctioned package manager, and is most commonly used to install packages published on the Python Package Index (PyPI). Both pip and PyPI are governed and supported by the Python Packaging Authority (PyPA).
In short, pip is a general-purpose manager for Python packages; conda is a language-agnostic cross-platform environment manager. For the user, the most salient distinction is probably this: pip installs python packages within any environment; conda installs any package within conda environments. If all you are doing is installing Python packages within an isolated environment, conda and pip+virtualenv are mostly interchangeable, modulo some difference in dependency handling and package availability. By isolated environment I mean a conda-env or virtualenv, in which you can install packages without modifying your system Python installation.
Even setting aside Myth #2, if we focus on just installation of Python packages, conda and pip serve different audiences and different purposes. If you want to, say, manage Python packages within an existing system Python installation, conda can't help you: by design, it can only install packages within conda environments. If you want to, say, work with the many Python packages which rely on external dependencies (NumPy, SciPy, and Matplotlib are common examples), while tracking those dependencies in a meaningful way, pip can't help you: by design, it manages Python packages and only Python packages.
Conda and pip are not competitors, but rather tools focused on different groups of users and patterns of use.
The ASCII table is arranged so that the value of the character '9'
is nine greater than the value of '0'
; the value of the character '8'
is eight greater than the value of '0'
; and so on.
So you can get the int value of a decimal digit char by subtracting '0'
.
char x = '9';
int y = x - '0'; // gives the int value 9
Cause all the other answer are not invented by me, here just my implementation:
public enum Range
{
/// <summary>
/// A range that contains all values greater than start and less than end.
/// </summary>
Open,
/// <summary>
/// A range that contains all values greater than or equal to start and less than or equal to end.
/// </summary>
Closed,
/// <summary>
/// A range that contains all values greater than or equal to start and less than end.
/// </summary>
OpenClosed,
/// <summary>
/// A range that contains all values greater than start and less than or equal to end.
/// </summary>
ClosedOpen
}
public static class RangeExtensions
{
/// <summary>
/// Checks if a value is within a range that contains all values greater than start and less than or equal to end.
/// </summary>
/// <param name="value">The value that should be checked.</param>
/// <param name="start">The first value of the range to be checked.</param>
/// <param name="end">The last value of the range to be checked.</param>
/// <returns><c>True</c> if the value is greater than start and less than or equal to end, otherwise <c>false</c>.</returns>
public static bool IsWithin<T>(this T value, T start, T end) where T : IComparable<T>
{
return IsWithin(value, start, end, Range.ClosedOpen);
}
/// <summary>
/// Checks if a value is within the given range.
/// </summary>
/// <param name="value">The value that should be checked.</param>
/// <param name="start">The first value of the range to be checked.</param>
/// <param name="end">The last value of the range to be checked.</param>
/// <param name="range">The kind of range that should be checked. Depending on the given kind of range the start end end value are either inclusive or exclusive.</param>
/// <returns><c>True</c> if the value is within the given range, otherwise <c>false</c>.</returns>
public static bool IsWithin<T>(this T value, T start, T end, Range range) where T : IComparable<T>
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (start == null)
throw new ArgumentNullException(nameof(start));
if (end == null)
throw new ArgumentNullException(nameof(end));
switch (range)
{
case Range.Open:
return value.CompareTo(start) > 0
&& value.CompareTo(end) < 0;
case Range.Closed:
return value.CompareTo(start) >= 0
&& value.CompareTo(end) <= 0;
case Range.OpenClosed:
return value.CompareTo(start) > 0
&& value.CompareTo(end) <= 0;
case Range.ClosedOpen:
return value.CompareTo(start) >= 0
&& value.CompareTo(end) < 0;
default:
throw new ArgumentException($"Unknown parameter value {range}.", nameof(range));
}
}
}
You can then use it like this:
var value = 5;
var start = 1;
var end = 10;
var result = value.IsWithin(start, end, Range.Closed);
just in case you need to create thumb with a max width and a max height ...
function makeThumbnails($updir, $img, $id,$MaxWe=100,$MaxHe=150){
$arr_image_details = getimagesize($img);
$width = $arr_image_details[0];
$height = $arr_image_details[1];
$percent = 100;
if($width > $MaxWe) $percent = floor(($MaxWe * 100) / $width);
if(floor(($height * $percent)/100)>$MaxHe)
$percent = (($MaxHe * 100) / $height);
if($width > $height) {
$newWidth=$MaxWe;
$newHeight=round(($height*$percent)/100);
}else{
$newWidth=round(($width*$percent)/100);
$newHeight=$MaxHe;
}
if ($arr_image_details[2] == 1) {
$imgt = "ImageGIF";
$imgcreatefrom = "ImageCreateFromGIF";
}
if ($arr_image_details[2] == 2) {
$imgt = "ImageJPEG";
$imgcreatefrom = "ImageCreateFromJPEG";
}
if ($arr_image_details[2] == 3) {
$imgt = "ImagePNG";
$imgcreatefrom = "ImageCreateFromPNG";
}
if ($imgt) {
$old_image = $imgcreatefrom($img);
$new_image = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresized($new_image, $old_image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
$imgt($new_image, $updir."".$id."_t.jpg");
return;
}
}
If you're using NotificationCompat.Builder
(a part of android.support.v4
) then simply call its object's method setAutoCancel
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setAutoCancel(true);
Some guys were reporting that setAutoCancel()
did not work for them, so you may try this way as well
builder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
Note that the method getNotification()
has been deprecated!!!
A matrix is really just a vector with a dim
attribute (for the dimensions). So you can add dimensions to vec
using the dim()
function and vec
will then be a matrix:
vec <- 1:49
dim(vec) <- c(7, 7) ## (rows, cols)
vec
> vec <- 1:49
> dim(vec) <- c(7, 7) ## (rows, cols)
> vec
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 1 8 15 22 29 36 43
[2,] 2 9 16 23 30 37 44
[3,] 3 10 17 24 31 38 45
[4,] 4 11 18 25 32 39 46
[5,] 5 12 19 26 33 40 47
[6,] 6 13 20 27 34 41 48
[7,] 7 14 21 28 35 42 49
object
is an easy alternative in HTML5:
<object data="https://github.com/AbrarJahin/Asp.NetCore_3.1-PostGRE_Role-Claim_Management/"
width="400"
height="300"
type="text/html">
Alternative Content
</object>
_x000D_
You can also try embed
:
<embed src="https://github.com/AbrarJahin/Asp.NetCore_3.1-PostGRE_Role-Claim_Management/"
width=200
height=200
onerror="alert('URL invalid !!');" />
_x000D_
As currently, StackOverflow has turned off support for showing external URL contents, run code snippet
is not showing anything. But for your site, it will work perfactly.
const fs = require('fs');
fs.stat('input.txt', function (err, stats) {
if(err){
console.log(err);
} else {
console.log(stats);
console.log('Completed Reading File');
}
});
'fs' is a node module which helps you to read file. Callback function will make sure that your file named 'input.txt' is completely read before it gets executed. fs.stat() function is to get file information like file size, date created and date modified.
The easiest way to strip all leading 0
s is:
var s = "00test";
s = s.replace(/^0+/, "");
If just stripping a single leading 0
character, as the question implies, you could use
s = s.replace(/^0/, "");
Adding a padding between the divs to simulate a gap might be a hack, but why not use something Bootstrap provides. It's called offsets. But again, you can define a class in your custom.css (you shouldn't edit the core stylesheet anyway) file and add something like .gap
. However, .col-md-offset-*
does the job most of the times for me, allowing me to precisely leave a gap between the divs.
As for vertical spacing, unfortunately, there isn't anything set built-in like that in Bootstrap 3, so you will have to invent your own custom class to do that. I'd usually do something like .top-buffer { margin-top:20px; }
. This does the trick, and obviously, it doesn't have to be 20px, it can be anything you like.
npm install node-sass
will do the job in most of the cases, as it will add missing sass npm dependency module doesn't exist or it will overwrite previous crashed version.
For Mac Users use sudo
in front of above commands.
On Windows machines npm rebuild node-sass --force
may not work for some users because it's essentially saying, "please force npm to rebuild the sass node module for me". It will not work because that module doesn't exist.
Whenever you did npm install
to the initial installation, the sass module did not get installed, which is why this problem occurs.
Try wrapping the spans in an anchor tag and apply the background image to that.
HTML:
<div class="header">
<a href="/">
<span class="header-title">My gray sea design</span><br />
<span class="header-title-two">A beautiful design</span>
</a>
</div>
CSS:
.header {
border-bottom:1px solid #eaeaea;
}
.header a {
display: block;
background-image: url("./images/embouchure.jpg");
background-repeat: no-repeat;
height:160px;
padding-left:280px;
padding-top:50px;
width:470px;
color: #eaeaea;
}
[ -~]
It was seen here. It matches all ASCII characters from the space to the tilde.
So your implementation would be:
xxx[ -~]+xxx
Easiest and correct way on a single line:
sqlite3 old.db ".dump mytable" | sqlite3 new.db
The primary key and the columns types will be kept.
It means "not equal to" (as in, the values in cells E37-N37 are not equal to ""
, or in other words, they are not empty.)
I think tir38's answer is the cleanest solution. Have in mind that if you are using android.app.AlerDialog and holo themes your style should look like this
<style name="WrapEverythingDialog" parent=[holo theme ex. android:Theme.Holo.Dialog]>
<item name="windowMinWidthMajor">0dp</item>
<item name="windowMinWidthMinor">0dp</item>
</style>
And if using support.v7.app.AlertDialog or androidx.appcompat.app.AlertDialog with AppCompat theme your style should look like this
<style name="WrapEverythingDialog" parent=[Appcompat theme ex. Theme.AppCompat.Light.Dialog.Alert]>
<item name="android:windowMinWidthMajor">0dp</item>
<item name="android:windowMinWidthMinor">0dp</item>
</style>
In order to avoid the black background when starting an activity already in the stack, I added
overridePendingTransition(0,0)
in onStart()
:
@Override
protected void onStart() {
overridePendingTransition(0,0);
super.onStart();
}
I got here looking for the inverse of your question, going from camel case to snake case. Use underscore for that (not decamelize):
AppUser.name.underscore # => "app_user"
or, if you already have a camel case string:
"AppUser".underscore # => "app_user"
or, if you want to get the table name, which is probably why you'd want the snake case:
AppUser.name.tableize # => "app_users"
You can try below:
find ./ ! \( -path ./tmp -prune \) ! \( -path ./scripts -prune \) -type f -name '*_peaks.bed'
Remove the display:none
, and use ng-show
instead:
<ul class="procedures">
<li ng-repeat="procedure in procedures | filter:query | orderBy:orderProp">
<h4><a href="#" ng-click="showDetails = ! showDetails">{{procedure.definition}}</a></h4>
<div class="procedure-details" ng-show="showDetails">
<p>Number of patient discharges: {{procedure.discharges}}</p>
<p>Average amount covered by Medicare: {{procedure.covered}}</p>
<p>Average total payments: {{procedure.payments}}</p>
</div>
</li>
</ul>
Here's the fiddle: http://jsfiddle.net/asmKj/
You can also use ng-class
to toggle a class:
<div class="procedure-details" ng-class="{ 'hidden': ! showDetails }">
I like this more, since it allows you to do some nice transitions: http://jsfiddle.net/asmKj/1/
Here is an example showing some text in circles with data from a json file: http://bl.ocks.org/4474971. Which gives the following:
The main idea behind this is to encapsulate the text and the circle in the same "div
" as you would do in html to have the logo and the name of the company in the same div
in a page header.
The main code is:
var width = 960,
height = 500;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
d3.json("data.json", function(json) {
/* Define the data for the circles */
var elem = svg.selectAll("g")
.data(json.nodes)
/*Create and place the "blocks" containing the circle and the text */
var elemEnter = elem.enter()
.append("g")
.attr("transform", function(d){return "translate("+d.x+",80)"})
/*Create the circle for each block */
var circle = elemEnter.append("circle")
.attr("r", function(d){return d.r} )
.attr("stroke","black")
.attr("fill", "white")
/* Create the text for each block */
elemEnter.append("text")
.attr("dx", function(d){return -20})
.text(function(d){return d.label})
})
and the json file is:
{"nodes":[
{"x":80, "r":40, "label":"Node 1"},
{"x":200, "r":60, "label":"Node 2"},
{"x":380, "r":80, "label":"Node 3"}
]}
The resulting html code shows the encapsulation you want:
<svg width="960" height="500">
<g transform="translate(80,80)">
<circle r="40" stroke="black" fill="white"></circle>
<text dx="-20">Node 1</text>
</g>
<g transform="translate(200,80)">
<circle r="60" stroke="black" fill="white"></circle>
<text dx="-20">Node 2</text>
</g>
<g transform="translate(380,80)">
<circle r="80" stroke="black" fill="white"></circle>
<text dx="-20">Node 3</text>
</g>
</svg>
If you want to register only one single key press even if the user pressed it for more than once or kept pressing the key longer. To avoid getting multiple pressed inputs use the while loop and pass it.
import keyboard
while(True):
if(keyboard.is_pressed('w')):
s+=1
while(keyboard.is_pressed('w')):
pass
if(keyboard.is_pressed('s')):
s-=1
while(keyboard.is_pressed('s')):
pass
print(s)
Go to IIS manager and click on the server name. Then click on the "ISAPI and CGI Restrictions" icon under the IIS header. Change ASP.NET 4.0 from "Not Allowed" to "Allowed".
Shortcut Alt+Enter shows intention actions where you can choose "Add Javadoc".
Without VBA macro, you can use this tips to get the username from the path :
=MID(INFO("DIRECTORY"),10,LEN(INFO("DIRECTORY"))-LEN(MID(INFO("DIRECTORY"),FIND("\",INFO("DIRECTORY"),10),1000))-LEN("C:\Users\"))
awk 'BEGIN {FS=" "} {printf "\047%s\047 ", $1}'
In the first situation, Num2
is extending the class Num
and since you are not redefining the special method named __init__()
in Num2
, it gets inherited from Num
.
When a class defines an
__init__()
method, class instantiation automatically invokes__init__()
for the newly-created class instance.
In the second situation, since you are redefining __init__()
in Num2
you need to explicitly call the one in the super class (Num
) if you want to extend its behavior.
class Num2(Num):
def __init__(self,num):
Num.__init__(self,num)
self.n2 = num*2
you can download USBview and get all the information you need. Along with the list of devices it will also show you the configuration of each device.
You are not passing your 2D array correctly. This should work for you
int rotateArr(int *arr[])
or
int rotateArr(int **arr)
or
int rotateArr(int arr[][N])
Rather than returning the array pass the target array as argument. See John Bode's answer.
Functions are first-class objects in Swift. So if you don't want to use a closure, you can also just define a function with the appropriate signature and then pass it as the handler
argument. Observe:
func someHandler(alert: UIAlertAction!) {
// Do something...
}
alert.addAction(UIAlertAction(title: "Okay",
style: UIAlertActionStyle.Default,
handler: someHandler))
I tried to do full compatible analog of javascript's encodeURIComponent for c# and after my 4 hour experiments I found this
c# CODE:
string a = "!@#$%^&*()_+ some text here ??? ??????? ????";
a = System.Web.HttpUtility.UrlEncode(a);
a = a.Replace("+", "%20");
the result is: !%40%23%24%25%5e%26*()_%2b%20some%20text%20here%20%d0%b0%d0%bb%d0%b8%20%d0%bc%d0%b0%d0%bc%d0%b5%d0%b4%d0%be%d0%b2%20%d0%b1%d0%b0%d0%ba%d1%83
After you decode It with Javascript's decodeURLComponent();
you will get this: !@#$%^&*()_+ some text here ??? ??????? ????
Thank You for attention
You don't have to use vectors. If you want to stick with plain arrays, you can do something like this:
int arr[] = new int[15];
unsigned int arr_length = 0;
Now, if you want to add an element to the end of the array, you can do this:
if (arr_length < 15) {
arr[arr_length++] = <number>;
} else {
// Handle a full array.
}
It's not as short and graceful as the PHP equivalent, but it accomplishes what you were attempting to do. To allow you to easily change the size of the array in the future, you can use a #define.
#define ARRAY_MAX 15
int arr[] = new int[ARRAY_MAX];
unsigned int arr_length = 0;
if (arr_length < ARRAY_MAX) {
arr[arr_length++] = <number>;
} else {
// Handle a full array.
}
This makes it much easier to manage the array in the future. By changing 15 to 100, the array size will be changed properly in the whole program. Note that you will have to set the array to the maximum expected size, as you can't change it once the program is compiled. For example, if you have an array of size 100, you could never insert 101 elements.
If you will be using elements off the end of the array, you can do this:
if (arr_length > 0) {
int value = arr[arr_length--];
} else {
// Handle empty array.
}
If you want to be able to delete elements off the beginning, (ie a FIFO), the solution becomes more complicated. You need a beginning and end index as well.
#define ARRAY_MAX 15
int arr[] = new int[ARRAY_MAX];
unsigned int arr_length = 0;
unsigned int arr_start = 0;
unsigned int arr_end = 0;
// Insert number at end.
if (arr_length < ARRAY_MAX) {
arr[arr_end] = <number>;
arr_end = (arr_end + 1) % ARRAY_MAX;
arr_length ++;
} else {
// Handle a full array.
}
// Read number from beginning.
if (arr_length > 0) {
int value = arr[arr_start];
arr_start = (arr_start + 1) % ARRAY_MAX;
arr_length --;
} else {
// Handle an empty array.
}
// Read number from end.
if (arr_length > 0) {
int value = arr[arr_end];
arr_end = (arr_end + ARRAY_MAX - 1) % ARRAY_MAX;
arr_length --;
} else {
// Handle an empty array.
}
Here, we are using the modulus operator (%) to cause the indexes to wrap. For example, (99 + 1) % 100 is 0 (a wrapping increment). And (99 + 99) % 100 is 98 (a wrapping decrement). This allows you to avoid if statements and make the code more efficient.
You can also quickly see how helpful the #define is as your code becomes more complex. Unfortunately, even with this solution, you could never insert over 100 items (or whatever maximum you set) in the array. You are also using 100 bytes of memory even if only 1 item is stored in the array.
This is the primary reason why others have recommended vectors. A vector is managed behind the scenes and new memory is allocated as the structure expands. It is still not as efficient as an array in situations where the data size is already known, but for most purposes the performance differences will not be important. There are trade-offs to each approach and it's best to know both.
append
adds an element to a list, and extend
concatenates the first list with another list (or another iterable, not necessarily a list.)
>>> li = ['a', 'b', 'mpilgrim', 'z', 'example']
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li.append("new")
>>> li
['a', 'b', 'mpilgrim', 'z', 'example', 'new']
>>> li.append(["new", 2])
>>> li
['a', 'b', 'mpilgrim', 'z', 'example', 'new', ['new', 2]]
>>> li.insert(2, "new")
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', ['new', 2]]
>>> li.extend(["two", "elements"])
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', ['new', 2], 'two', 'elements']
Code for python terminal progress bar
import sys
import time
max_length = 5
at_length = max_length
empty = "-"
used = "%"
bar = empty * max_length
for i in range(0, max_length):
at_length -= 1
#setting empty and full spots
bar = used * i
bar = bar+empty * at_length
#\r is carriage return(sets cursor position in terminal to start of line)
#\0 character escape
sys.stdout.write("[{}]\0\r".format(bar))
sys.stdout.flush()
#do your stuff here instead of time.sleep
time.sleep(1)
sys.stdout.write("\n")
sys.stdout.flush()
Thanks for the help everyone, but since i'm on HP-UX (after all: the more you pay, the less features you get...) i've had to resort to perl:
perl -e '@T=localtime(time-86400);printf("%02d/%02d/%04d",$T[3],$T[4]+1,$T[5]+1900)' | read dt
Just Remove the type="text/javascript"
<script src="JavaScript/jquery.js" />
<script src="JavaScript/bootstrap-min.js" />
Here is the update - http://jsfiddle.net/andieje/kRX6n/
Beware of recipes like this
target:
MY_ID=$(GENERATE_ID);
echo $MY_ID;
It does two things wrong. The first line in the recipe is executed in a separate shell instance from the second line. The variable is lost in the meantime. Second thing wrong is that the $
is not escaped.
target:
MY_ID=$(GENERATE_ID); \
echo $$MY_ID;
Both problems have been fixed and the variable is useable. The backslash combines both lines to run in one single shell, hence the setting of the variable and the reading of the variable afterwords, works.
I realize the original post said how to get the results of a shell command into a MAKE variable, and this answer shows how to get it into a shell variable. But other readers may benefit.
One final improvement, if the consumer expects an "environment variable" to be set, then you have to export it.
my_shell_script
echo $MY_ID
would need this in the makefile
target:
export MY_ID=$(GENERATE_ID); \
./my_shell_script;
Hope that helps someone. In general, one should avoid doing any real work outside of recipes, because if someone use the makefile with '--dry-run' option, to only SEE what it will do, it won't have any undesirable side effects. Every $(shell)
call is evaluated at compile time and some real work could accidentally be done. Better to leave the real work, like generating ids, to the inside of the recipes when possible.
float only has a max. precision of 15 digits. Digits after the 15th position are therefore random, and conversion to bigint (max. 19 digits) or decimal does not help you.
Just overwriting of getInputStream()
did not work in my case. My server implementation seems to parse parameters without calling this method. I did not find any other way, but re-implement the all four getParameter* methods as well. Here is the code of getParameterMap
(Apache Http Client and Google Guava library used):
@Override
public Map<String, String[]> getParameterMap() {
Iterable<NameValuePair> params = URLEncodedUtils.parse(getQueryString(), NullUtils.UTF8);
try {
String cts = getContentType();
if (cts != null) {
ContentType ct = ContentType.parse(cts);
if (ct.getMimeType().equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
List<NameValuePair> postParams = URLEncodedUtils.parse(IOUtils.toString(getReader()), NullUtils.UTF8);
params = Iterables.concat(params, postParams);
}
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
Map<String, String[]> result = toMap(params);
return result;
}
public static Map<String, String[]> toMap(Iterable<NameValuePair> body) {
Map<String, String[]> result = new LinkedHashMap<>();
for (NameValuePair e : body) {
String key = e.getName();
String value = e.getValue();
if (result.containsKey(key)) {
String[] newValue = ObjectArrays.concat(result.get(key), value);
result.remove(key);
result.put(key, newValue);
} else {
result.put(key, new String[] {value});
}
}
return result;
}
you can try this
pd.pandas.set_option('display.max_columns', None)
One thing to think about is: Do you have your WCF completely uncoupled from the WindowsService (WS)? A WS is painful because you don't have a lot of control or visibility to them. I try to mitigate this by having all of my non-WS stuff in their own classes so they can be tested independently of the host WS. Using this approach might help you eliminate anything that is happening with the WS runtime vs. your service in particular.
John is likely correct that it is a .config file problem. WCF will always look for the execution context .config. So if you are hosting your WCF in different execution contexts (that is, test with a console application, and deploy with a WS), you need to make sure you have WCF configuration data moved over to the proper .config file. But the underlying issue to me is that you don't know what the problem is because the WS goo gets in the way. If you haven't refactored to that yet so that you can run your service in any context (that is, unit test or console), then I'd sugget doing so. If you spun your service up in a unit test, it would likely fail the same way that you are seeing with the WS which is much easier to debug rather than attempting to do so with the yucky WS plumbing.
This is my function. JavaScript must be under PHP otherwise use SESSION.
<?php
$phpArray=array(1,2,3,4,5,6);
?>
<div id="arrayCon" style="width:300px;"></div>
<script type="text/javascript">
var jsArray = new Array();
<?php
$numArray=count($phpArray);
for($i=0;$i<$numArray;$i++){
echo "jsArray[$i] = ". $phpArray[$i] . ";\n";
}
?>
$("#arrayCon").text(jsArray[1]);
</script>
Last row can be ....text(jsArray); and will be shown "1,2,3,4,5,6"
You could replace something in there by getting the index along with the item.
>>> foo = ['a', 'b', 'c', 'A', 'B', 'C']
>>> for index, item in enumerate(foo):
... print(index, item)
...
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'A')
(4, 'B')
(5, 'C')
>>> for index, item in enumerate(foo):
... if item in ('a', 'A'):
... foo[index] = 'replaced!'
...
>>> foo
['replaced!', 'b', 'c', 'replaced!', 'B', 'C']
Note that if you want to remove something from the list you have to iterate over a copy of the list, else you will get errors since you're trying to change the size of something you are iterating over. This can be done quite easily with slices.
Wrong:
>>> foo = ['a', 'b', 'c', 1, 2, 3]
>>> for item in foo:
... if isinstance(item, int):
... foo.remove(item)
...
>>> foo
['a', 'b', 'c', 2]
The 2 is still in there because we modified the size of the list as we iterated over it. The correct way would be:
>>> foo = ['a', 'b', 'c', 1, 2, 3]
>>> for item in foo[:]:
... if isinstance(item, int):
... foo.remove(item)
...
>>> foo
['a', 'b', 'c']
Here is a long (easy to understand) version but takes care of leap years.
cheers, JK
def last_day_month(year, month):
leap_year_flag = 0
end_dates = {
1: 31,
2: 28,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31
}
# Checking for regular leap year
if year % 4 == 0:
leap_year_flag = 1
else:
leap_year_flag = 0
# Checking for century leap year
if year % 100 == 0:
if year % 400 == 0:
leap_year_flag = 1
else:
leap_year_flag = 0
else:
pass
# return end date of the year-month
if leap_year_flag == 1 and month == 2:
return 29
elif leap_year_flag == 1 and month != 2:
return end_dates[month]
else:
return end_dates[month]
Solutions in accepted answer are being deprecated
#4 Calling prop directly
Enzyme simulate is supposed to be removed in version 4. The main maintainer is suggesting directly invoking prop functions, which is what simulate does internally. One solution is to directly test that invoking those props does the right thing; or you can mock out instance methods, test that the prop functions call them, and unit test the instance methods.
You could call click, for example:
wrapper.find('Button').prop('onClick')()
Or
wrapper.find('Button').props().onClick()
Information about deprecation: Deprecation of .simulate() #2173
This will surely work .
To Disable a button
$('#btn_id').button('disable');
To Enable a button
$('#btn_id').button('enable');
Try using os.system
:
os.system("script2.py 1")
execfile
is different because it is designed to run a sequence of Python statements in the current execution context. That's why sys.argv
didn't change for you.
Answer for Mac Devices:
Go to
Applications/Utilities/Keychain Acccess
Search for git.credentials
, and delete the git credentials for the desired URL.
No redundant "return" array, no ECMA5 (I'm pretty sure!) and simple to read.
function removeDuplicates(target_array) {
target_array.sort();
var i = 0;
while(i < target_array.length) {
if(target_array[i] === target_array[i+1]) {
target_array.splice(i+1,1);
}
else {
i += 1;
}
}
return target_array;
}
It may be easier to use XPath to locate the nodes that you wish to delete. This stackoverflow thread might give you some ideas.
In your case you will find the four nodes that you want using this expression:
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']");
From the test,
it('should allow passing locals to the expression', inject(function($rootScope) {
expect($rootScope.$eval('a+1', {a: 2})).toBe(3);
$rootScope.$eval(function(scope, locals) {
scope.c = locals.b + 4;
}, {b: 3});
expect($rootScope.c).toBe(7);
}));
We also can pass locals for evaluation expression.
Check your Elastic version.
I had these problem because I was looking at the incorrect version's documentation.
Since the accepted answer does not allow more edits, I'm going to summarize it with a single copy-paste command (Replace 3.2.1 with the latest version available in the first line):
version="3.2.1" && \
wget "https://github.com/glfw/glfw/releases/download/${version}/glfw-${version}.zip" && \
unzip glfw-${version}.zip && \
cd glfw-${version} && \
sudo apt-get install cmake xorg-dev libglu1-mesa-dev && \
sudo cmake -G "Unix Makefiles" && \
sudo make && \
sudo make install
If you want to compile a program use the following commands:
g++ -std=c++11 -c main.cpp && \
g++ main.o -o main.exec -lGL -lGLU -lglfw3 -lX11 -lXxf86vm -lXrandr -lpthread -lXi -ldl -lXinerama -lXcursor
If you are following the learnopengl.com tutorial you may have to set up GLAD as well. In such case click on this link
and then click on the "Generate" button at the bottom right corner of the website and download the zip file. Extract it and compile the sources with the following command:
g++ glad/src/glad.c -c -Iglad/include
Now, the commands to compile your program become like this:
g++ -std=c++11 -c main.cpp -Iglad/include && \
g++ main.o glad.o -o main.exec -lGL -lGLU -lglfw3 -lX11 -lXxf86vm -lXrandr -lpthread -lXi -ldl -lXinerama -lXcursor
Found this approach on another site. It works with the new larger sizes of Excel and doesn't require you to hardcode the max number of rows and columns.
iLastRow = Cells(Rows.Count, "a").End(xlUp).Row
iLastCol = Cells(i, Columns.Count).End(xlToLeft).Column
If you want to display some buttons with actions when an list item is swipe are a lot of libraries on the internet that have this behavior. I implemented the library that I found on the internet and I am very satisfied. It is very simple to use and very quick. I improved the original library and I added a new click listener for item click. Also I added font awesome library (http://fortawesome.github.io/Font-Awesome/) and now you can simply add a new item title and specify the icon name from font awesome.
Here is the github link
What I found out is that it's OK to put char* into a std::vector:
// 1 - A std::vector of char*, more preper way is to use a std::vector<std::vector<char>> or std::vector<std::string>
std::vector<char*> v(10, "hi!"); // You cannot put standard library containers e.g. char[] into std::vector!
for (auto& i : v)
{
//std::cout << i << std::endl;
i = "New";
}
for (auto i : v)
{
std::cout << i << std::endl;
}
The answer is given in @dku-rajkumar post.
ArrayList commonList = CollectionUtils.retainAll(list1,list2);
Improving on Gordon Wilson solution, here is my try:
def to_time
#Convert a fraction of a day to a number of microseconds
usec = (sec_fraction * 60 * 60 * 24 * (10**6)).to_i
t = Time.gm(year, month, day, hour, min, sec, usec)
t - offset.abs.div(SECONDS_IN_DAY)
end
You'll get the same time in UTC, loosing the timezone (unfortunately)
Also, if you have ruby 1.9, just try the to_time
method
It actually tells you what's wrong, but you ignored it because you didn't check the error returned from json.Marshal
.
json: unsupported type: map[int]main.Foo
JSON spec doesn't support anything except strings for object keys, while javascript won't be fussy about it, it's still illegal.
You have two options:
1 Use map[string]Foo
and convert the index to string (using fmt.Sprint for example):
datas := make(map[string]Foo, N)
for i := 0; i < 10; i++ {
datas[fmt.Sprint(i)] = Foo{Number: 1, Title: "test"}
}
j, err := json.Marshal(datas)
fmt.Println(string(j), err)
2 Simply just use a slice (javascript array):
datas2 := make([]Foo, N)
for i := 0; i < 10; i++ {
datas2[i] = Foo{Number: 1, Title: "test"}
}
j, err = json.Marshal(datas2)
fmt.Println(string(j), err)
You can manually set this using Laravel, just remember to add 'created_at' to your $fillable array:
protected $fillable = ['name', 'created_at'];
Your application is not able to connect to activemq. Check that your activemq is running and listening on localhost 61616.
You can try using: netstat -a
to check if the activemq process has started. Or try check if you can access your actvemq using admin page: localhost:8161/admin/queues.jsp
On mac you will start your activemq using:
$ACTMQ_HOME/bin/activemq start
Or if your config file (activemq.xml ) if located in another location you can use:
$ACTMQ_HOME/bin/activemq start xbean:file:${location_of_your_config_file}
In your case the executable is under: bin/macosx/activemq
so you need to use: $ACTMQ_HOME/bin/macosx/activemq start
In your Startup.Auth.cs file add this line:
LoginPath = new PathString("/Account/Login"),
Example:
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
I found that the first solution in the accepted answer to be problematic for cases where the newline character is still required. The easiest solution to the problem was doing this:
numpy.savetxt(filename, [a], delimiter='\t')
It is recommended to check default terminal shell before set JAVA_HOME environment variable, via following commands:
$ echo $SHELL
/bin/bash
If your default terminal is /bin/bash (Bash), then you should use @Adrian Petrescu method.
If your default terminal is /bin/zsh (Z Shell), then you should set these environment variable in ~/.zshenv file with following contents:
export JAVA_HOME="$(/usr/libexec/java_home)"
Similarly, any other terminal type not mentioned above, you should set environment variable in its respective terminal env file.
try this. (I modified the example on the purpose of making it non trivial)
import operator
import numpy as np
n=10
a = list(range(n))
a1 = [1]*len(a)
an = np.array(a)
operator.add
is almost more than two times faster
%timeit map(operator.add, a, a1)
than adding with numpy
%timeit an+1
three different approaches:
Classic client/server approach: don't put any database in the shops; simply have the applications access your server. Of course it's better if you set a VPN, but simply wrapping the connection in SSL or ssh is reasonable. Pro: it's the way databases were originally thought. Con: if you have high latency, complex operations could get slow, you might have to use stored procedures to reduce the number of round trips.
replicated master/master: as @Book Of Zeus suggested. Cons: somewhat more complex to setup (especially if you have several shops), breaking in any shop machine could potentially compromise the whole system. Pros: better responsivity as read operations are totally local and write operations are propagated asynchronously.
offline operations + sync step: do all work locally and from time to time (might be once an hour, daily, weekly, whatever) write a summary with all new/modified records from the last sync operation and send to the server. Pros: can work without network, fast, easy to check (if the summary is readable). Cons: you don't have real-time information.
Just for the record, I got borders in the table and to get rid of it I needed to set following properties in the GridView:
GridLines="None"
CellSpacing="-1"
This error can occur when you trying to install pycurl
.
In this case you should do
sudo apt-get install libcurl4-gnutls-dev librtmp-dev
(founded here: https://gist.github.com/lxneng/1031014 )
hi @JackSlayer94 please find the below example to understand how to make an array of size 5.
class Hero {_x000D_
name: string;_x000D_
constructor(text: string) {_x000D_
this.name = text;_x000D_
}_x000D_
_x000D_
display() {_x000D_
return "Hello, " + this.name;_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
let heros:Hero[] = new Array(5);_x000D_
for (let i = 0; i < 5; i++){_x000D_
heros[i] = new Hero("Name: " + i);_x000D_
}_x000D_
_x000D_
for (let i = 0; i < 5; i++){_x000D_
console.log(heros[i].display());_x000D_
}
_x000D_
1) What is an API?
API is a contract. A promise to perform described services when asked in specific ways.
2) How is it used?
According to the rules specified in the contract. The whole point of an API is to define how it's used.
3) When and where is it used?
It's used when 2 or more separate systems need to work together to achieve something they can't do alone.
let's say you want to add CSS to my active state/tab. Use routerLinkActive to activate your routing link.
note : 'active' is my class name here
<style>
.active{
color:blue;
}
</style>
<a routerLink="/home" [routerLinkActive]="['active']">Home</a>
<a routerLink="/about" [routerLinkActive]="['active']">About</a>
<a routerLink="/contact" [routerLinkActive]="['active']">Contact</a>
From what I've found online, this is a bug introduced in JDK 1.7.0_45. It appears to also be present in JDK 1.7.0_60. A bug report on Oracle's website states that, while there was a fix, it was removed before the JDK was released. I do not know why the fix was removed, but it confirms what we've already suspected -- the JDK is still broken.
The bug report claims that the error is benign and should not cause any run-time problems, though one of the comments disagrees with that. In my own experience, I have been able to work without any problems using JDK 1.7.0_60 despite seeing the message.
If this issue is causing serious problems, here are a few things I would suggest:
Revert back to JDK 1.7.0_25 until a fix is added to the JDK.
Keep an eye on the bug report so that you are aware of any work being done on this issue. Maybe even add your own comment so Oracle is aware of the severity of the issue.
Try the JDK early releases as they come out. One of them might fix your problem.
Instructions for installing the JDK on Mac OS X are available at JDK 7 Installation for Mac OS X. It also contains instructions for removing the JDK.
Adding this option for dealing with basic uint8 to byte[] conversion
foo := 255 // 1 - 255
ufoo := uint16(foo)
far := []byte{0,0}
binary.LittleEndian.PutUint16(far, ufoo)
bar := int(far[0]) // back to int
fmt.Println("foo, far, bar : ",foo,far,bar)
output :
foo, far, bar : 255 [255 0] 255
As Tyler points out, there's no way to do what you require "directly and reliably", since a given FD may correspond to 0 filenames (in various cases) or > 1 (multiple "hard links" is how the latter situation is generally described). If you do still need the functionality with all the limitations (on speed AND on the possibility of getting 0, 2, ... results rather than 1), here's how you can do it: first, fstat the FD -- this tells you, in the resulting struct stat
, what device the file lives on, how many hard links it has, whether it's a special file, etc. This may already answer your question -- e.g. if 0 hard links you will KNOW there is in fact no corresponding filename on disk.
If the stats give you hope, then you have to "walk the tree" of directories on the relevant device until you find all the hard links (or just the first one, if you don't need more than one and any one will do). For that purpose, you use readdir (and opendir &c of course) recursively opening subdirectories until you find in a struct dirent
thus received the same inode number you had in the original struct stat
(at which time if you want the whole path, rather than just the name, you'll need to walk the chain of directories backwards to reconstruct it).
If this general approach is acceptable, but you need more detailed C code, let us know, it won't be hard to write (though I'd rather not write it if it's useless, i.e. you cannot withstand the inevitably slow performance or the possibility of getting != 1 result for the purposes of your application;-).
var userPasswordString = new Buffer(baseAuth, 'base64').toString('ascii');
Change this line from your code to this -
var userPasswordString = Buffer.from(baseAuth, 'base64').toString('ascii');
or in my case, I gave the encoding in reverse order
var userPasswordString = Buffer.from(baseAuth, 'utf-8').toString('base64');
As a general rule, pop up blockers target windows that launch without user interaction. Usually a click event can open a window without it being blocked. (unless it's a really bad popup blocker)
Try launching after a click event
Using cwolves' answer, but not using a closure nor a pre-computed hash :
// Golfed it a bit, too...
function readCookie(n){
var c = document.cookie.split('; '),
i = c.length,
C;
for(; i>0; i--){
C = c[i].split('=');
if(C[0] == n) return C[1];
}
}
...and minifying...
function readCookie(n){var c=document.cookie.split('; '),i=c.length,C;for(;i>0;i--){C=c[i].split('=');if(C[0]==n)return C[1];}}
...equals 127 bytes.
TRUE
and FALSE
are keywords, and should not be quoted as strings:
INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);
By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT
in MySQL), which translates into zero for any non-numeric string. Thus, you get 0
for both values in your table.
mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
| 0 | 0 | 12345 |
+------------------------+-------------------------+-------------------------+
INT
representation:mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
| 1 | 0 |
+------+-------+
Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id
with NULL
. The empty string may issue a warning.
read this;-
http://php.net/manual/en/soapclient.call.php
Or
This is a good example, for the SOAP function "__call". However it is deprecated.
<?php
$wsdl = "http://webservices.tekever.eu/ctt/?wsdl";
$int_zona = 5;
$int_peso = 1001;
$cliente = new SoapClient($wsdl);
print "<p>Envio Internacional: ";
$vem = $cliente->__call('CustoEMSInternacional',array($int_zona, $int_peso));
print $vem;
print "</p>";
?>
The Placeholder does not render any tags for itself, so it is great for grouping content without the overhead of outer HTML tags.
The Panel does have outer HTML tags but does have some cool extra properties.
BackImageUrl: Gets/Sets the background image's URL for the panel
HorizontalAlign: Gets/Sets the
horizontal alignment of the parent's
contents
There is a good article at startvbnet here.
docker
groupsudo usermod -aG docker $USER
/var/run/docker.sock
sudo chmod 666 /var/run/docker.sock
You want to check the result of scanf() to make sure there was a successful conversion; if there wasn't, then one of three things is true:
Example:
int moreData = 1;
...
printf("Input no: ");
fflush(stdout);
/**
* Loop while moreData is true
*/
while (moreData)
{
errno = 0;
int itemsRead = scanf("%f", &input);
if (itemsRead == 1)
{
printf("Output: %f\n", input);
printf("Input no: ");
fflush(stdout);
}
else
{
if (feof(stdin))
{
printf("Hit EOF on stdin; exiting\n");
moreData = 0;
}
else if (ferror(stdin))
{
/**
* I *think* scanf() sets errno; if not, replace
* the line below with a regular printf() and
* a generic "read error" message.
*/
perror("error during read");
moreData = 0;
}
else
{
printf("Bad character stuck in input stream; clearing to end of line\n");
while (getchar() != '\n')
; /* empty loop */
printf("Input no: ");
fflush(stdout);
}
}
Change string[] lines = File.ReadLines("c:\\file.txt");
to IEnumerable<string> lines = File.ReadLines("c:\\file.txt");
The rest of your code should work fine.
I feel like there should be a no javascript solution, but how is this?
$(window).resize(function() {
$('#content').height($(window).height() - 46);
});
$(window).trigger('resize');
Create a test utility method. Specially useful if you need it for more than once.
@Test
public void testMyTest() {
// ...
Foo<Bar> mockFooBar = mockFoo();
when(mockFooBar.getValue).thenReturn(new Bar());
Foo<Baz> mockFooBaz = mockFoo();
when(mockFooBaz.getValue).thenReturn(new Baz());
Foo<Qux> mockFooQux = mockFoo();
when(mockFooQux.getValue).thenReturn(new Qux());
// ...
}
@SuppressWarnings("unchecked") // still needed :( but just once :)
private <T> Foo<T> mockFoo() {
return mock(Foo.class);
}
At the time of writing this, the current version of Tomcat 7 (7.0.41) has a built-in CORS filter http://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#CORS_Filter
foreach (GridViewRow gvr in gvMyGridView.Rows)
{
string PrimaryKey = gvMyGridView.DataKeys[gvr.RowIndex].Values[0].ToString();
}
You can use this code while doing an iteration with foreach
or for any GridView event like OnRowDataBound
.
Here you can input multiple values for DataKeyNames
by separating with comma ,
. For example, DataKeyNames="ProductID,ItemID,OrderID"
.
You can now access each of DataKeys
by providing its index like below:
string ProductID = gvMyGridView.DataKeys[gvr.RowIndex].Values[0].ToString();
string ItemID = gvMyGridView.DataKeys[gvr.RowIndex].Values[1].ToString();
string OrderID = gvMyGridView.DataKeys[gvr.RowIndex].Values[2].ToString();
You can also use Key Name instead of its index to get the values from DataKeyNames
collection like below:
string ProductID = gvMyGridView.DataKeys[gvr.RowIndex].Values["ProductID"].ToString();
string ItemID = gvMyGridView.DataKeys[gvr.RowIndex].Values["ItemID"].ToString();
string OrderID = gvMyGridView.DataKeys[gvr.RowIndex].Values["OrderID"].ToString();
You can easily find the size of each of your repository in your Accounts settings
The comment by MK pointed me in the right direction.
In the case of Apache 2.4 and up, there are different defaults and a new directive.
I am running Apache 2.4.6, and I had to add the following directives to get it working:
SSLProxyEngine on
SSLProxyVerify none
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
SSLProxyCheckPeerExpire off
Well, I guess if you need to remove an element you will make a copy of the array despising the element to be excluded.
// inserting some items
void* element_2_remove = getElement2BRemove();
for (int i = 0; i < vector->size; i++){
if(vector[i]!=element_2_remove) copy2TempVector(vector[i]);
}
free(vector->items);
free(vector);
fillFromTempVector(vector);
//
Assume that getElement2BRemove()
, copy2TempVector( void* ...)
and fillFromTempVector(...)
are auxiliary methods to handle the temp vector.
There are no vertical lines in html that you can use but you can fake one by absolutely positioning a div outside of your container with a top:0;
and bottom:0;
style.
Try this:
CSS
.vr {
width:10px;
background-color:#000;
position:absolute;
top:0;
bottom:0;
left:150px;
}
HTML
<div class="vr"> </div>
In Kotlin we can create array using arrayOf()
, intArrayOf()
, charArrayOf()
, booleanArrayOf()
, longArrayOf()
functions.
For example:
var Arr1 = arrayOf(1,10,4,6,15)
var Arr2 = arrayOf<Int>(1,10,4,6,15)
var Arr3 = arrayOf<String>("Surat","Mumbai","Rajkot")
var Arr4 = arrayOf(1,10,4, "Ajay","Prakesh")
var Arr5: IntArray = intArrayOf(5,10,15,20)
I wrote this answer about four years ago and my opinion hasn't changed. But since then there have been significant developments on the micro-services front. I added micro-services specific notes at the end...
I'll weigh in against the idea, with real-world experience to back up my vote.
I was brought on to a large application that had five contexts for a single database. In the end, we ended up removing all of the contexts except for one - reverting back to a single context.
At first the idea of multiple contexts seems like a good idea. We can separate our data access into domains and provide several clean lightweight contexts. Sounds like DDD, right? This would simplify our data access. Another argument is for performance in that we only access the context that we need.
But in practice, as our application grew, many of our tables shared relationships across our various contexts. For example, queries to table A in context 1 also required joining table B in context 2.
This left us with a couple poor choices. We could duplicate the tables in the various contexts. We tried this. This created several mapping problems including an EF constraint that requires each entity to have a unique name. So we ended up with entities named Person1 and Person2 in the different contexts. One could argue this was poor design on our part, but despite our best efforts, this is how our application actually grew in the real world.
We also tried querying both contexts to get the data we needed. For example, our business logic would query half of what it needed from context 1 and the other half from context 2. This had some major issues. Instead of performing one query against a single context, we had to perform multiple queries across different contexts. This has a real performance penalty.
In the end, the good news is that it was easy to strip out the multiple contexts. The context is intended to be a lightweight object. So I don't think performance is a good argument for multiple contexts. In almost all cases, I believe a single context is simpler, less complex, and will likely perform better, and you won't have to implement a bunch of work-arounds to get it to work.
I thought of one situation where multiple contexts could be useful. A separate context could be used to fix a physical issue with the database in which it actually contains more than one domain. Ideally, a context would be one-to-one to a domain, which would be one-to-one to a database. In other words, if a set of tables are in no way related to the other tables in a given database, they should probably be pulled out into a separate database. I realize this isn't always practical. But if a set of tables are so different that you would feel comfortable separating them into a separate database (but you choose not to) then I could see the case for using a separate context, but only because there are actually two separate domains.
Regarding micro-services, one single context still makes sense. However, for micro-services, each service would have its own context which includes only the database tables relevant to that service. In other words, if service x accesses tables 1 and 2, and service y accesses tables 3 and 4, each service would have its own unique context which includes tables specific to that service.
I'm interested in your thoughts.
It's even simpler: just use dataSrc:''
option in the ajax defintion so dataTable knows to expect an array instead of an object:
$('#pos-table2').DataTable({
processing: true,
serverSide: true,
ajax:{url:"pos.json",dataSrc:""}
}
);
See ajax options
This is explained in Apple's documentation, but below are some examples of what is actually happening.
Note that there is no "atomic" keyword, if you do not specify "nonatomic", then the property is atomic, but specifying "atomic" explicitly will result in an error.
If you do not specify "nonatomic", then the property is atomic, but you can still specify "atomic" explicitly in recent versions if you want to.
//@property(nonatomic, retain) UITextField *userName;
//Generates roughly
- (UITextField *) userName {
return userName;
}
- (void) setUserName:(UITextField *)userName_ {
[userName_ retain];
[userName release];
userName = userName_;
}
Now, the atomic variant is a bit more complicated:
//@property(retain) UITextField *userName;
//Generates roughly
- (UITextField *) userName {
UITextField *retval = nil;
@synchronized(self) {
retval = [[userName retain] autorelease];
}
return retval;
}
- (void) setUserName:(UITextField *)userName_ {
@synchronized(self) {
[userName_ retain];
[userName release];
userName = userName_;
}
}
Basically, the atomic version has to take a lock in order to guarantee thread safety, and also is bumping the ref count on the object (and the autorelease count to balance it) so that the object is guaranteed to exist for the caller, otherwise there is a potential race condition if another thread is setting the value, causing the ref count to drop to 0.
There are actually a large number of different variants of how these things work depending on whether the properties are scalar values or objects, and how retain, copy, readonly, nonatomic, etc interact. In general the property synthesizers just know how to do the "right thing" for all combinations.
If you want to print the last 10 lines, use
tail(dataset, 10)
for the first 10, you could also do
head(dataset, 10)
If your CString is Unicode, you'll need to do a conversion to multi-byte characters. Fortunately there is a version of CString which will do this automatically.
CString unicodestr = _T("Testing");
CStringA charstr(unicodestr);
DoMyStuff((const char *) charstr);