mysql group_concat group by on multiple fields

I have a Table member with member_id, member_name, club_name, region, zone, email as fields.

I am using the MySQL group_concat function like

SELECT group_concat(distinct m.email
SEPARATOR ', ' ) from member m group by m.club_name

This is working fine. But I would like to be able to group_concat on other fields without creating additional queries.

Is it possible to supply the other fields as parameter?

member_id   member_name club_name   region  zone    email
1           member1           A        1    1   email1@example.com
2           member2           A        1    1   email2@example.com
3           member3           B        1    1   email3@example.com
4           member4           C        1    2   email4@example.com
5           member5           D        2    1   email5@example.com

**group by club**
email1@example.com,email2@example.com
email3@example.com
email4@example.com
email5@example.com

**group by region**
email1@example.com, email2@example.com, email3@example.com, email4@example.com
email5@example.com

**group by zone**
email1@example.com, email2@example.com, email3@example.com
email5@example.com

Say every Region has 3 Zones, every zone has more than one club. Now how can I get emails which can be grouped or related to Region, Zone or Club for that matter?

# # These are settings for Heroku Production Environment # from .common import * import dj_database_url # We don't want any debug warnings giving # away unnecessary information to attackers DEBUG = False # We grab the secret key from the environment because it is # our production key and no can know it SECRET_KEY = os.environ.get('SECRET_KEY') # We redirect any http requests to their https equivalents SECURE_SSL_REDIRECT = True ALLOWED_HOSTS = ["yefbackend.herokuapp.com", "localhost"] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ # In a real production environment, we would likely want to # handle static files on a different machine. STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # We let the dj_database_url package pull the database info from heroku # https://github.com/kennethreitz/dj-database-url DATABASES = { 'default': dj_database_url.config(conn_max_age=600, ssl_require=True) } REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': DEFAULT_RENDERER_CLASSES } CORS_ORIGIN_WHITELIST = ( 'localhost:3000', 'yefclient.herokuapp.com' ) """ """ from __future__ import division from torch.optim.optimizer import Optimizer, required import numpy as np import torch from typing import NamedTuple, List from dataclasses import dataclass from enum import Enum from typing import Union, Tuple # from scipy.sparse.linalg import svds from scipy.optimize import minimize_scalar class LayerType(Enum): CONV = 1 FC = 2 NON_CONV = 3 @dataclass class LayerMetrics: rank: float KG: float condition: float @dataclass class ConvLayerMetrics: input_channel: LayerMetrics output_channel: LayerMetrics class LRMetrics(NamedTuple): rank_velocity: List[float] r_conv: List[float] def EVBMF(Y, sigma2=None, H=None): """Implementation of the analytical solution to Empirical Variational Bayes Matrix Factorization. This function can be used to calculate the analytical solution to empirical VBMF. This is based on the paper and MatLab code by Nakajima et al.: "Global analytic solution of fully-observed variational Bayesian matrix factorization." Notes ----- If sigma2 is unspecified, it is estimated by minimizing the free energy. If H is unspecified, it is set to the smallest of the sides of the input Y. Attributes ---------- Y : numpy-array Input matrix that is to be factorized. Y has shape (L,M), where L<=M. sigma2 : int or None (default=None) Variance of the noise on Y. H : int or None (default = None) Maximum rank of the factorized matrices. Returns ------- U : numpy-array Left-singular vectors. S : numpy-array Diagonal matrix of singular values. V : numpy-array Right-singular vectors. post : dictionary Dictionary containing the computed posterior values. References ---------- .. [1] Nakajima, Shinichi, et al. "Global analytic solution of fully-observed variational Bayesian matrix factorization." Journal of Machine Learning Research 14.Jan (2013): 1-37. .. [2] Nakajima, Shinichi, et al. "Perfect dimensionality recovery by variational Bayesian PCA." Advances in Neural Information Processing Systems. 2012. """ L, M = Y.shape # has to be L<=M if H is None: H = L alpha = L / M tauubar = 2.5129 * np.sqrt(alpha) # SVD of the input matrix, max rank of H # U, s, V = np.linalg.svd(Y) U, s, V = torch.svd(Y) U = U[:, :H] s = s[:H] V = V[:H].T # Calculate residual residual = 0. if H < L: # residual = np.sum(np.sum(Y**2)-np.sum(s**2)) residual = torch.sum(np.sum(Y**2) - np.sum(s**2)) Chaturanga () is a 2008 Indian Bengali-language film directed by Suman Mukherjee, starring Rituparna Sengupta, Dhritiman Chaterji, Subrata Dutta, Joy Sengupta and Kabir Suman. Based on the 1916 novel, Chaturanga, by author Rabindranath Tagore the film is about a love caught between conflicting worlds of ideas. Plot Set in Colonial Bengal at the turn of the twentieth century, the film weaves a rich tapestry of crisscrossing desires and moralities. The protagonist Sachish fleets from radical positivism to religious mysticism in his quest for life's meaning. However, his search ultimately yields nothing but crushing disillusionment. This is because he cannot square his abstract ideals with the powerful presences of two women in his life. One of them is Damini, a young Hindu widow, and the other is Nanibala, the abandoned mistress of Sachish's own brother. Sachish tries to convince himself that Nanibala is simply a helpless woman who needs to be 'rescued' by him. Similarly, during his later religious phase, he pretends that the widow Damini is merely an enticement of Nature that must be avoided at all costs for spiritual salvation. Chaturanga thus becomes, after a point, a psychodrama of cruelty. Nanibala becomes a victim of it because as a 'fallen woman' she can only be 'saved', but her humanity cannot be recognized. Damini is first given away by her dying husband, along with all her property, to a religious guru. She then falls in love with Sachish who can accept her only without her sexuality. Cast Dhritiman Chaterji ... Uncle Rituparna Sengupta ... Damini Subrat Dutta ... Shachish Joy Sengupta ... Shribilash Kabir Suman ... Lilananda Trina Nileena Banerjee ... Nanibala Music The songs, especially those from the Vaishnav tradition, are erotic. The divine is expressed in them through allegorical depictions of the illicit love between Krishna and Radha, who was actually his aunt. There is a radical side to this blend of eroticism and divinity. Radha's love for Krishna is beyond all social norms. It is directly expressed, without the priest or the Brahmin caste coming in between. When devotees sing and rejoice in that form of love, it is thus a popular and democratic process that defies caste divisions. "Allah Ke Nur—Shafqat" — Amaanat Ali & Chorus "Din Thakte Tiner Sadhan" — Kartick Das Baul "Bhajo Patito Udhadharana"— Arijit Chakraborty & Chorus "Hara Gauri Prananath" — Dohar "Esraj" — Instrumental "Hari Haraye Nama" — Monomoy Chakraborty & Chorus "Jagohu Brishobhanu" — Sri Bani Kumar Chatterjee & Chorus "Hese Khele Nao Re Jogu" — Neel Mukherjee & Chorus "Rupo Lagi Aankhi Jhure" — Raghab Chatterjee "Joy Radhe Radhe" — Arijit Chakraborty & Chorus "Moula Tere Bina" — Shafqat Amaanat Ali & Chorus "Nirodo Nayane" — Santa Das "Background Music" — Instrumental "Praner Majhe Sudha (Hum)" — Parama Banerjee "Radha Madhabo" — Kabir Suman & Chorus "Aalo Je Amar Gaan Kore" — Parama Banerjee References External links Official Website VBA hash string

How do I get a short hash of a long string using Excel VBA?

What's given

What I have done so far

I thought this SO answer is a good start since it generates a 4-digit Hex-Code (CRC16).

But 4 digits were too few. In my test with 400 strings, 20% got a duplicate somewhere else.
The chance to generate a collision is too high.

Sub tester()
    For i = 2 To 433
        Cells(i, 2) = CRC16(Cells(i, 1))
    Next i
End Sub


Function CRC16(txt As String)
Dim x As Long
Dim mask, i, j, nC, Crc As Integer
Dim c As String

Crc = &HFFFF

For nC = 1 To Len(txt)
    j = Val("&H" + Mid(txt, nC, 2))
    Crc = Crc Xor j
    For j = 1 To 8
        mask = 0
        If Crc / 2 <> Int(Crc / 2) Then mask = &HA001
        Crc = Int(Crc / 2) And &H7FFF: Crc = Crc Xor mask
    Next j
Next nC

CRC16 = Hex$(Crc)
End Function

How to reproduce

You can copy these 400 test strings from pastebin.
Paste them to column A in a new Excel workbook and execute the code above.

Q: How do I get a string hash which is short enough (12 chars) and long enough to get a small percentage of duplicates.

nginx proxy pass to external url

I have configured my nginx on amazon ec2 for the url www.example1.com . I need to proxy pass www.example1.com/blog to my blogging host www.example2.com/blog which is hosted on bluehost ( shred hosting ) without changing the url in browser. Is it possible ?

I tried many different combinations like

location /blog {
    proxy_pass http://www.example2.com;
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

without any luck.

I could see in the log that nginx is trying to map to the IP instead of the domain which is the reason for the failure as shared hosting cannot recognize the ip but domain name.

Any input/help will be really appreciated.

#ifndef DFM2_OPENGL_OLD_TEX_H #define DFM2_OPENGL_OLD_TEX_H #include "delfem2/opengl/tex.h" #include "delfem2/opengl/old/funcs.h" #include "delfem2/mat3.h" #include "delfem2/mat4.h" namespace delfem2::opengl { namespace tex { template T Dot3(const T *p0, const T *p1){ return p0[0]*p1[0] + p0[1]*p1[1] + p0[2]*p1[2]; } } void DrawTexMaxSize( const delfem2::opengl::CTexRGB &tex0) { ::glEnable(GL_TEXTURE_2D); ::glBindTexture(GL_TEXTURE_2D, tex0.id_tex); glColor3f(1.f, 1.f, 1.f); glBegin(GL_QUADS); ::glTexCoord2d(0, 0); glVertex2f(-1, +1); ::glTexCoord2d(1, 0); glVertex2f(+1, +1); ::glTexCoord2d(1, 1); glVertex2f(+1, -1); ::glTexCoord2d(0, 1); glVertex2f(-1, -1); glEnd(); } void DrawTextureBackground() { ::glEnable(GL_TEXTURE_2D); ::glMatrixMode(GL_PROJECTION); ::glPushMatrix(); ::glLoadIdentity(); ::glMatrixMode(GL_MODELVIEW); ::glPushMatrix(); ::glLoadIdentity(); ::glDisable(GL_LIGHTING); ::glColor3d(1,1,1); ::glBegin(GL_QUADS); ::glTexCoord2d(0,+1); ::glVertex2d(-1,+1); ::glTexCoord2d(+1,+1); ::glVertex2d(+1,+1); ::glTexCoord2d(+1,0); ::glVertex2d(+1,-1); ::glTexCoord2d(0,0); ::glVertex2d(-1,-1); ::glEnd(); ::glDisable(GL_TEXTURE_2D); ::glMatrixMode(GL_PROJECTION); ::glPopMatrix(); ::glMatrixMode(GL_MODELVIEW); ::glPopMatrix(); } void DrawCamInteriorMatrixWithTexture( const delfem2::opengl::CTexRGB &tex0, const float Kinv[9], float tex_loc_z) { ::glEnable(GL_TEXTURE_2D); const float ax[4][3] = { {0.f, 0.f, 1.f}, {float(tex0.width), 0.f, 1.f}, {float(tex0.width), float(tex0.height), 1.f}, {0.f, float(tex0.height), 1.f}}; float aX[4][3]; for (unsigned int i = 0; i < 4; ++i) { delfem2::MatVec3(aX[i], Kinv, ax[i]); const float a = tex_loc_z / aX[i][2]; aX[i][0] *= a; aX[i][1] *= a; aX[i][2] = tex_loc_z; } ::glBindTexture(GL_TEXTURE_2D, tex0.id_tex); glColor3f(1.f, 1.f, 1.f); glBegin(GL_QUADS); ::glTexCoord2d(0, 0); glVertex3fv(aX[0]); ::glTexCoord2d(1, 0); glVertex3fv(aX[1]); ::glTexCoord2d(1, 1); glVertex3fv(aX[2]); ::glTexCoord2d(0, 1); glVertex3fv(aX[3]); glEnd(); // ::glColor3d(0, 0, 0); ::glBegin(GL_LINES); glVertex3fv(aX[0]); glVertex3d(0, 0, 0); glVertex3fv(aX[1]); glVertex3d(0, 0, 0); glVertex3fv(aX[2]); glVertex3d(0, 0, 0); glVertex3fv(aX[3]); glVertex3d(0, 0, 0); ::glEnd(); } void DrawCam( const delfem2::opengl::CTexRGB &tex0, const float R[9], const float t[3], const float K[9]) { ::glMatrixMode(GL_MODELVIEW); ::glPushMatrix(); float A[16]; delfem2::Mat4_AffineTrans_RotTransl( A, R, t); ::glMultMatrixf(A); float Kinv[9]; delfem2::Inverse_Mat3(Kinv, K); DrawCamInteriorMatrixWithTexture(tex0, Kinv, -1.f); delfem2::opengl::DrawAxis(1); ::glPopMatrix(); } /* eslint-disable @typescript-eslint/no-misused-promises */ import { makeAddSurveyController, makeListSurveysController } from '@/main/composers/controllers' import { makeAuthMiddleware } from '@/main/composers/middlewares' import { adaptController, adaptMiddleware } from '@/main/adapters' import { Router } from 'express' export default (router: Router): void => { router.route('/survey') .post(adaptMiddleware(makeAuthMiddleware('admin')), adaptController(makeAddSurveyController())) .get(adaptMiddleware(makeAuthMiddleware()), adaptController(makeListSurveysController())) } [: -gt: unary operator expected

I don't write a lot of Bash, so I'm a bit stumped as to how to fix this. I need to check whether a value returned from a command is greater than x. When it runs though I get [: -gt: unary operator expected which I'm unable to fix.

Here is my script,

#!/bin/sh
ERROR=0
PHPCPDLevel=100

# PHPCPD
echo "PHP CopyPaste Detection (Limit is at least ${PHPCPDLevel}%"
PHPCPD="phpcpd ."
if [[ `echo $PHPCPD | grep "%" | cut -d'.' -f1` -gt "$PHPCPDLevel" ]]
  then
    echo $PHPCPD
    ERROR=1
  else
    echo "... -> Only `echo $PHPCPD | grep "%" | cut -d'.' -f1`%"
fi

echo "Finished!"
exit $ERROR

Update: I think I've done it:

#!/bin/sh
ERROR=0
PHPCPDLevel=25

# PHPCPD
echo "PHP CopyPaste Detection (Limit is at most ${PHPCPDLevel}%)"
PHPCPD="phpcpd ."
PERCENTAGE=$($PHPCPD | grep "%" | cut -d'.' -f1)
if [ ${PERCENTAGE} -gt ${PHPCPDLevel} ]
  then
    echo $PHPCPD
    ERROR=1
  else
    echo "Only $PERCENTAGE%"
fi

exit $ERROR
Anarchism is a political philosophy and movement that is skeptical of all justifications for authority and seeks to abolish the institutions it claims maintain unnecessary coercion and hierarchy, typically including nation-states, and capitalism. Anarchism advocates for the replacement of the state with stateless societies and voluntary free associations. As a historically left-wing movement, this reading of anarchism is placed on the farthest left of the political spectrum, usually described as the libertarian wing of the socialist movement (libertarian socialism). Humans have lived in societies without formal hierarchies long before the establishment of states, realms, or empires. With the rise of organised hierarchical bodies, scepticism toward authority also rose. Although traces of anarchist ideas are found all throughout history, modern anarchism emerged from the Enlightenment. During the latter half of the 19th and the first decades of the 20th century, the anarchist movement flourished in most parts of the world and had a significant role in workers' struggles for emancipation. Various anarchist schools of thought formed during this period. Anarchists have taken part in several revolutions, most notably in the Paris Commune, the Russian Civil War and the Spanish Civil War, whose end marked the end of the classical era of anarchism. In the last decades of the 20th and into the 21st century, the anarchist movement has been resurgent once more, growing in popularity and influence within anti-capitalist, anti-war and anti-globalisation movements. Anarchists employ diverse approaches, which may be generally divided into revolutionary and evolutionary strategies; there is significant overlap between the two. Evolutionary methods try to simulate what an anarchist society might be like, but revolutionary tactics, which have historically taken a violent turn, aim to overthrow authority and the state. Many facets of human civilization have been influenced by anarchist theory, critique, and praxis. Etymology, terminology, and definition The etymological origin of anarchism is from the Ancient Greek anarkhia, meaning "without a ruler", composed of the prefix an- ("without") and the word arkhos ("leader" or "ruler"). The suffix -ism denotes the ideological current that favours anarchy. Anarchism appears in English from 1642 as anarchisme and anarchy from 1539; early English usages emphasised a sense of disorder. Various factions within the French Revolution labelled their opponents as anarchists, although few such accused shared many views with later anarchists. Many revolutionaries of the 19th century such as William Godwin (1756–1836) and Wilhelm Weitling (1808–1871) would contribute to the anarchist doctrines of the next generation but did not use anarchist or anarchism in describing themselves or their beliefs. SOAP Response Schema Validation

Short version:

I'm trying to write an XSD that will validate my SOAP service's responses. I feel compelled to just import http:// schemas.xmlsoap.org/soap/envelope/ instead of redefining the SOAP elements like Envelope, Head, and Body, but that xmlsoap.org schema definition of Body is too broad for my use--as soon as I import the SOAP Schema, suddenly my XSD (that I've carefully tailored to my service) validates all SOAP messages.

How should I handle the definition of the SOAP envelope, head, body in my XSD?

I suspect the problem is that I'm trying to re-use other schemas that I shouldn't be trying to re-use. Certainly, those Schemas for SOAP are intended to define what (all) SOAP messages should look like. And maybe I just need to define in my schema what I want my particular soap body to look like.

I might have just answered my own question. Maybe someone has a different solution?

Long version:

I'm having a little trouble authoring an XSD to describe the response message from one of my SOAP services.

Here's an example response from my service that I'm trying to validate:

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <helloResponse xmlns="http://justinfaulkner/wsdl/1.0">
         <Message>Hello, Justin!</Message>
         <Message>Your lucky numbers are: 329, 9</Message>
      </helloResponse>
   </soap:Body>
</soap:Envelope>

My goal is to validate responses from my service with an XSD. So, I hand-authored an XSD that describes all the types that belong in my service's soap:Body

<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://justinfaulkner/wsdl/1.0" xmlns:tns="http://justinfaulkner/wsdl/1.0">
   <xsd:complexType name="helloResponseType">
      <xsd:sequence>
         <xsd:element name="Message" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
      </xsd:sequence>
   </xsd:complexType>
   <xsd:element name="helloResponse" type="tns:helloResponseType"/>
</xsd:schema>

When I tried to validate the example response (first XML snippet) with the Schema (2nd snippet) using PHP's DOMDocument::schemaValidateSource() functionality, the validator pointed out my first obvious mistake:

Element 'soap:Envelope': No matching global declaration available

"Oops, duh," I thought, "Those elements are defined in SOAP's namespace, so I need to import SOAP's XSD."

So I edited my XSD and added an import:

Custom serializer for serializing a List in List

I've a Model object Group

public class Group {
    String title;
    List<User> members;
    String createdBy;
}

I'm using Jackson to serialize this Object. Instead of serializing the whole User object in list "members" I want to serializer just the user.getTitle() field. Basically I want a HashMap to be something like

{
  "title" : "sometitle"
  "members" : [user1.getTitle(), user2.getTitle()]
}

I've written a custom serializer for this

public class GroupSerializer extends JsonSerializer<Circle> {

    @Override
    public void serialize(Group value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {

        if(value != null) {
            gen.writeStartObject();
            gen.writeStringField("title", value.getTitle());
            gen.writeStringField("createdBy", value.getCreatedBy());
            gen.writeFieldName("members");
            gen.writeStartArray();
            for(User user : value.getMembers()) {
                gen.writeString(user.getEmail());
            }
            gen.writeEndArray();
            gen.writeEndObject()
        }
   }
}

But it's not working. How do I serialize only a field of List instead of whole User Object?

// Copyright 2015 Keybase, Inc. All rights reserved. Use of // this source code is governed by the included BSD license. package keybase1 import ( "bytes" "crypto/hmac" "crypto/sha256" "crypto/sha512" "crypto/subtle" "encoding/base64" "encoding/binary" "encoding/hex" "encoding/json" "errors" "fmt" "regexp" "sort" "strconv" "strings" "time" "github.com/keybase/go-framed-msgpack-rpc/rpc" jsonw "github.com/keybase/go-jsonw" ) const ( UID_LEN = 16 UID_SUFFIX = 0x00 UID_SUFFIX_2 = 0x19 UID_SUFFIX_HEX = "00" UID_SUFFIX_2_HEX = "19" TEAMID_LEN = 16 TEAMID_PRIVATE_SUFFIX = 0x24 TEAMID_PRIVATE_SUFFIX_HEX = "24" TEAMID_PUBLIC_SUFFIX = 0x2e TEAMID_PUBLIC_SUFFIX_HEX = "2e" SUB_TEAMID_PRIVATE_SUFFIX = 0x25 SUB_TEAMID_PRIVATE_SUFFIX_HEX = "25" SUB_TEAMID_PUBLIC_SUFFIX = 0x2f SUB_TEAMID_PUBLIC_SUFFIX_HEX = "2f" PUBLIC_UID = "ffffffffffffffffffffffffffffff00" ) // UID for the special "public" user. var PublicUID = UID(PUBLIC_UID) const ( SIG_ID_LEN = 32 SIG_ID_SUFFIX = 0x0f SIG_SHORT_ID_BYTES = 27 SigIDQueryMin = 8 ) const ( DeviceIDLen = 16 DeviceIDSuffix = 0x18 DeviceIDSuffixHex = "18" ) const ( KidLen = 35 // bytes KidSuffix = 0x0a // a byte KidVersion = 0x1 ) func Unquote(data []byte) string { return strings.Trim(string(data), "\"") } func Quote(s string) []byte { return []byte("\"" + s + "\"") } func UnquoteBytes(data []byte) []byte { return bytes.Trim(data, "\"") } func KIDFromSlice(b []byte) KID { return KID(hex.EncodeToString(b)) } func (b BinaryKID) ToKID() KID { return KIDFromSlice([]byte(b)) } func (k KID) ToBinaryKID() BinaryKID { return BinaryKID(k.ToBytes()) } func KIDFromStringChecked(s string) (KID, error) { // It's OK to have a 0-length KID. That means, no such key // (or NULL kid). if len(s) == 0 { return KID(""), nil } b, err := hex.DecodeString(s) if err != nil { return KID(""), err } if len(b) != KidLen { return KID(""), fmt.Errorf("KID wrong length; wanted %d but got %d bytes", KidLen, len(b)) } if b[len(b)-1] != KidSuffix { return KID(""), fmt.Errorf("Bad KID suffix: got 0x%02x, wanted 0x%02x", b[len(b)-1], KidSuffix) } if b[0] != KidVersion { return KID(""), fmt.Errorf("Bad KID version; got 0x%02x but wanted 0x%02x", b[0], KidVersion) } return KID(s), nil } func HashMetaFromString(s string) (ret HashMeta, err error) { // TODO: Should we add similar handling to other types? if s == "null" { return nil, nil } b, err := hex.DecodeString(s) if err != nil { return ret, err } return HashMeta(b), nil } func KBFSRootHashFromString(s string) (ret KBFSRootHash, err error) { if s == "null" { return nil, nil } b, err := base64.StdEncoding.DecodeString(s) if err != nil { return ret, err } return KBFSRootHash(b), nil } ### User: write a rust function that reads a file line by line and counts word frequencies, return a HashMap ### Assistant: ```rust use std::collections::HashMap; use std::fs::File; use std::io::{self, BufRead, BufReader}; /// Reads a file line by line and returns word frequencies. /// Words are lowercased; whitespace is the separator. pub fn word_frequencies(path: &str) -> io::Result> { let file = File::open(path)?; let reader = BufReader::new(file); let mut freq: HashMap = HashMap::new(); for line in reader.lines() { let line = line?; for word in line.split_whitespace() { let normalized = word .trim_matches(|c: char| !c.is_alphanumeric()) .to_lowercase(); if !normalized.is_empty() { *freq.entry(normalized).or_insert(0) += 1; } } } Ok(freq) } ``` Note the `BufReader` — without it every line triggers a syscall and large files crawl. For multi-gigabyte files, bump the capacity: `BufReader::with_capacity(1 << 20, file)`. Kalinkavichy (; ; ) is a town in Gomel Region, southeastern Belarus. It serves as the administrative center of Kalinkavichy District. Kalinkavichy is located beside the Netech' River, opposite the town of Mazyr, and is the site of one of the country's most important railway junctions. It has a population of 37,876 (2004 estimate). It has suffered radioactive fallout from the Chernobyl disaster. History Archaeological excavations have found traces of human settlement dating back to 26,000-24,000 years ago, the oldest yet discovered in Belarus. The earliest historical mention of the town of Kalinkavičy dates to 1560. The town grew to prominence at the end of the nineteenth century with the coming of the railways. Before World War II, a significant part of the population was Jewish, 3,386 out of 9,799 were Jews. Kalinkavichy was under German occupation from 22 August 1941 until 14 January 1944. Before the arrival of the German forces, a part of the Jewish population managed to evacuate the city by train. On September 20, 1941, all the Jews were shot by collaborating policemen and German gendarmes in a trench. Food processing (esp. pork products) is the largest industry. The extraction of peat (5.5 million tonnes of reserves) is also economically important. Overview The mean January temperature is ; July . Precipitation totals per annum. Kalinkavičy is also known for the annual Avtyuki comedy festival, held every June. In 1998, the town was united with the surrounding rural area to form a single administrative unit, Kalinkavičy Rajon, covering , with a total population of 71,500. Notable people One of the most notable figures born in Kalinkavicy was Solomon Simon (1895–1970), a well-known Yiddish author who emigrated to New York City in 1913. His autobiography, "My Jewish Roots," describes his early childhood years in Kalinkavichy (Kalinkovich). Katherine Locke, a stage and supporting screen actress of the 1930s and 40s was born in Kalinkavichy, prior to emigrating to the United States. IDF General (1905-1947) References External links Youtube: 3 июля 2018 года. КАЛИНКОВИЧИ ОТМЕТИЛИ ДЕНЬ НЕЗАВИСИМОСТИ Populated places in Gomel Region Towns in Belarus Minsk Voivodeship Rechitsky Uyezd Kalinkavichy District const Git = require('./git'); const filenamify = require('filenamify-url'); const copy = require('./util').copy; const getUser = require('./util').getUser; const fs = require('fs-extra'); const globby = require('globby'); const path = require('path'); const util = require('util'); const log = util.debuglog('gh-pages'); function getCacheDir() { return path.relative(process.cwd(), path.resolve(__dirname, '../.cache')); } function getRepo(options) { if (options.repo) { return Promise.resolve(options.repo); } else { const git = new Git(process.cwd(), options.git); return git.getRemoteUrl(options.remote); } } exports.defaults = { dest: '.', add: false, git: 'git', depth: 1, dotfiles: false, branch: 'gh-pages', remote: 'origin', src: '**/*', only: '.', push: true, history: true, message: 'Updates', silent: false, getCacheDir }; /** * Push a git branch to a remote (pushes gh-pages by default). * @param {string} basePath The base path. * @param {Object} config Publish options. * @param {Function} callback Callback. */ exports.publish = function publish(basePath, config, callback) { if (typeof config === 'function') { callback = config; config = {}; } const options = Object.assign({}, exports.defaults, config); if (!callback) { callback = function(err) { if (err) { log(err.message); } }; } function done(err) { try { callback(err); } catch (err2) { log('Publish callback threw: %s', err2.message); } } try { if (!fs.statSync(basePath).isDirectory()) { done(new Error('The "base" option must be an existing directory')); return; } } catch (err) { done(err); return; } const files = globby .sync(options.src, { cwd: basePath, dot: options.dotfiles }) .filter(file => { return !fs.statSync(path.join(basePath, file)).isDirectory(); }); if (!Array.isArray(files) || files.length === 0) { done( new Error('The pattern in the "src" property didn\'t match any files.') ); return; } const only = globby.sync(options.only, {cwd: basePath}).map(file => { return path.join(options.dest, file); }); begin_class specifier|public class|class name|DestinationFilterVirtualDestinationMatcher implements|implements name|VirtualDestinationMatcher block|{ comment|/* (non-Javadoc) * @see org.apache.activemq.advisory.VirtualDestinationMatcher#matches(org.apache.activemq.broker.region.virtual.VirtualDestination) */ annotation|@ name|Override specifier|public name|boolean name|matches parameter_list|( name|VirtualDestination name|virtualDestination parameter_list|, name|ActiveMQDestination name|activeMQDest parameter_list|) block|{ if|if condition|( name|virtualDestination operator|instanceof name|CompositeDestination condition|) block|{ name|DestinationFilter name|filter init|= name|DestinationFilter operator|. name|parseFilter argument_list|( name|virtualDestination operator|. name|getMappedDestinations argument_list|() argument_list|) decl_stmt|; if|if condition|( name|filter operator|. name|matches argument_list|( name|activeMQDest argument_list|) condition|) block|{ return|return literal|true return|; block|} block|} elseif|else if|if condition|( name|virtualDestination operator|instanceof name|VirtualTopic condition|) block|{ name|DestinationFilter name|filter init|= name|DestinationFilter operator|. name|parseFilter argument_list|( operator|new name|ActiveMQQueue argument_list|( operator|( operator|( name|VirtualTopic operator|) name|virtualDestination operator|) operator|. name|getPrefix argument_list|() operator|+ name|DestinationFilter operator|. name|ANY_DESCENDENT argument_list|) argument_list|) decl_stmt|; if|if condition|( name|filter operator|. name|matches argument_list|( name|activeMQDest argument_list|) condition|) block|{ return|return literal|true return|; block|} block|} return|return literal|false return|; block|} block|} end_class end_unit // Count number of particles to send to each process kkLidView num_send_particles("num_send_particles", comm_size + 1); auto count_sending_particles = PS_LAMBDA(const lid_t& element_id, const lid_t& particle_id, const bool& mask) { const lid_t process = new_process(particle_id); if (mask && (process != comm_rank)) { const lid_t process_index = dist.index(process); Kokkos::atomic_increment(&num_send_particles(process_index)); } }; parallel_for(count_sending_particles); //********* Send # of particles being sent to each process kkLidView num_recv_particles("num_recv_particles", comm_size + 1); int num_send_ranks = dist.isWorld() ? 0 : comm_size - 1; MPI_Request* count_send_requests = NULL; if (num_send_ranks > 0) count_send_requests = new MPI_Request[num_send_ranks]; int num_recv_ranks = dist.isWorld() ? 1 : comm_size - 1; MPI_Request* count_recv_requests = new MPI_Request[num_recv_ranks]; if (dist.isWorld()) PS_Comm_Ialltoall(num_send_particles, 1, num_recv_particles, 1, dist.mpi_comm(), count_recv_requests); else { int request_index = 0; for (int i = 0; i < comm_size; ++i) { int rank = dist.rank_host(i); if (rank != comm_rank) { PS_Comm_Isend(num_send_particles, i, 1, rank, 0, dist.mpi_comm(), count_send_requests + request_index); PS_Comm_Irecv(num_recv_particles, i, 1, rank, 0, dist.mpi_comm(), count_recv_requests + request_index); ++request_index; } } } // Gather sending particle data // Perform an ex-sum on num_send_particles & num_recv_particles kkLidView offset_send_particles("offset_send_particles", comm_size+1); kkLidView offset_send_particles_temp(Kokkos::ViewAllocateWithoutInitializing("offset_send_particles_temp"), comm_size + 1); exclusive_scan(num_send_particles, offset_send_particles); Kokkos::deep_copy(offset_send_particles_temp, offset_send_particles); kkLidHostMirror offset_send_particles_host = deviceToHost(offset_send_particles); Named Pipe CreateFile() returns INVALID_HANDLE_VALUE, and GetLastError() returns ERROR_PIPE_BUSY

I have written a class to handle named pipe connections, and if I create an instance, close it, and then try to create another instance the call to CreateFile() returns INVALID_HANDLE_VALUE, and GetLastError() returns ERROR_PIPE_BUSY. What's going on here? What can I do to insure the call to Connect() succeeds?

PipeAsync A, B;

A.Connect("\\\\.\\pipe\\test",5000);
A.Close();

cout << GetLastError(); // some random value
B.Connect("\\\\.\\pipe\\test",5000);
cout << GetLastError(); // 231 (ERROR_PIPE_BUSY)
B.Close(); 

Here are my implementations of Connect() and Close()

BOOL PipeAsync::Connect(LPCSTR pszPipeName, DWORD dwTimeout)
{
    this->pszPipeName = pszPipeName;
    this->fExisting = TRUE;
    DWORD dwMode = this->fMessageMode ? PIPE_READMODE_MESSAGE : PIPE_READMODE_BYTE;

    hPipe = CreateFile(
        this->pszPipeName,
        GENERIC_READ | GENERIC_WRITE,
        0,
        NULL,
        OPEN_EXISTING,
        FILE_FLAG_OVERLAPPED,
        NULL);

    if( INVALID_HANDLE_VALUE == hPipe )
        return FALSE; /* set break point here ; breaks here on second call to Connect() */

    if( GetLastError() == ERROR_PIPE_BUSY )
        if(!WaitNamedPipe( this->pszPipeName, dwTimeout ))
            return FALSE; /* set break point here */

    if( !SetNamedPipeHandleState( hPipe, &dwMode, NULL, NULL ) )
        return FALSE; /* set break point here */

    return TRUE;

}

VOID PipeAsync::Close()
{

    if( fExisting )
        DisconnectNamedPipe( hPipe );

    CloseHandle( hPipe );
}



EDIT: I forgot to tell you how I concluded this... I set break points indicated in the comments. When run, it stops on the first break point.

EDIT: This is my updated code

if( INVALID_HANDLE_VALUE == hPipe )
    if( GetLastError() == ERROR_PIPE_BUSY )
    {
        if(!WaitNamedPipe( this->pszPipeName, dwTimeout ))
            return FALSE; /* break-point: breaks here on second call */
    }
    else
        return FALSE; /* break-point /*

Now, WaitNamedPipe() is returning false on the second call to Connect() and GetLastError() is returning 2, or ERROR_FILE_NOT_FOUND ?

The Whanganui Rugby Football Union (WRFU) is the governing body for rugby union in the Whanganui region of New Zealand. The Whanganui Rugby Football Union was formed in 1888. The Whanganui team play from Cooks Gardens, Whanganui, and have enjoyed much success on the playing field throughout their history. Although not a First division team they are one of the leading provinces in terms of the number of lower divisional titles won. History The Whanganui Rugby Football Union was formed on 11 April 1888. It then joined the NZRFU as a foundation member in 1892. Wanganui's first official game after affiliation with the NZRFU was against the British and Irish Lions in 1888, with a 1–1 draw being more than encouraging for the union. In 1913 Whanganui played Australia and won 11-6 and in 1966 (with King Country) they won against touring side, British and Irish Lions 12–6. Clubs Wanganui Rugby Football Union is made up of 13 clubs: Counties Border Hunterville Kaierau Marist Marton Rugby and Sports Club Ngamatapouri Ratana Ruapehu Taihape Utiku Old Boys Wanganui Pirates Wanganui Tech Championships Whanganui previously played in the Second division North Island provincial competition and subsequently in the National Provincial Championship (NPC) Third division. In 2006 when the national rugby competitions were restructured, Whanganui entered the Heartland Championship, a competition for New Zealand's smaller provincial unions. They have been regular winners or finalists of Heartland trophies. Honours 1976 National Provincial Championship Second Division Runners Up 1982 National Provincial Championship Second Division Runners Up. 1983 National Provincial Championship Second Division Runners Up 1984 National Provincial Championship Second Division Runners Up 1989 National Provincial Championship Third Division Champions 1996 National Provincial Championship Third Division Champions 2003 National Provincial Championship Third Division Champions 2006 Heartland Championship Meads Cup Runners Up 2007 Heartland Championship Meads Cup Runners Up 2008 Heartland Championship Meads Cup Champions 2009 Heartland Championship Meads Cup Champions 2010 Heartland Championship Meads Cup Runners Up 2011 Heartland Championship Meads Cup Champions 2012 Heartland Championship Meads Cup Runners Up 2014 Heartland Championship Lochore Cup Champions 2015 Heartland Championship Meads Cup Champions 2016 Heartland Championship Meads Cup Champions 2017 Heartland Championship Meads Cup Champions 2018 Heartland Championship (S/F) Meads Cup 2019 Heartland Championship Meads Cup Runners Up 2020 Heartland Championship - NO COMPETITION - 2021 Heartland Championship Lochore Cup Champions Heartland Championship Placings Copy Data From One Table To Another AND Adding Additional Data

I have a temp table and a regular table in my database. The column name and types are identical, except the regular table has an extra field. I am trying to write a query that copies the information from the temp table into the regular table and adds data into the addition field all in one query.

I understand how to copy columns from one table to another (e.g. INSERT INTO TABLE 1 (col 1, etc..) SELECT TABLE2), but how do i do this AND then add in a the value for the new field?

Thanks for your help.

INSERT INTO IIS.ESTABLISHMENT ( PK_ESTABLISHMENT_CODE, ESTABLISHMENT_NAME, ESTAB_CNA, ESTAB_OP_CAP, ESTAB_ADDRESS_LINE_1, ESTAB_ADDRESS_LINE_2, ESTAB_ADDRESS_LINE_3, ESTAB_ADDRESS_LINE_4, ESTAB_POSTCODE, GENERAL_TEL_NO, TEAM_ID, FAX_NUMBER, TRANSACTION_SEQ_NUMBER, XIDBKEY, XILDID, XIDB) VALUES ('BA', 'BELMARSH ', 0, 0, 'WESTERN WAY ', 'THAMESMEAD ', 'LONDON ', ' ', 'SE28 0EB', '020 83314400', 7, '020 83314401', 1612497, 128454657, 170216, ' '), ('DM', 'DURHAM ', 0, 0, 'OLD ELVET ', 'DURHAM ', ' ', ' ', 'DH1 3HU ', '0191 3323400', 1, '0191 3323401', 1061381, 128399617, 170216, ' '), ('FK', 'FRANKLAND ', 0, 0, 'BRASSIDE ', 'DURHAM ', ' ', ' ', 'DH1 5YD ', '0191 3765000', 1, '0191 3765001', 93043, 128216578, 170216, ' '), ('FN', 'FULL SUTTON ', 0, 0, 'FULL SUTTON ', 'YORK ', ' ', ' ', 'YO41 1PS', '01759 475100', 1, '01759 371206', 97888, 128608001, 170216, ' '), ('LL', 'LONG LARTIN ', 0, 0, 'SHINEHILL LANE ', 'SOUTH LITTLETON ', 'EVESHAM ', 'WORCESTERSHIRE ', 'WR11 8TZ', '01386 295100', 5, '01386 295101', 62864, 128079105, 170216, ' '), ('WD', 'WAKEFIELD ', 0, 0, '5 LOVE LANE ', 'WAKEFIELD ', 'WEST YORKSHIRE ', ' ', 'WF2 9AG ', '01924 612000', 1, '01924 612001', 56136, 128460801, 170216, ' '), ('HV', 'HILL VALLEY ', 0, 0, '10 COURTHOUSE SQUARE ', 'HILL VALLEY ', 'CALIFORNIA ', ' ', '90210', '555 19851955', 1, '555 19851955', 56136, 128460801, 170216, ' ') ; GO class DesktopSessionProxy::IpcSharedBuffer : public webrtc::SharedMemory { public: IpcSharedBuffer(scoped_refptr core) : SharedMemory(core->memory(), core->size(), core->handle(), core->id()), core_(core) { } private: scoped_refptr core_; DISALLOW_COPY_AND_ASSIGN(IpcSharedBuffer); }; DesktopSessionProxy::DesktopSessionProxy( scoped_refptr audio_capture_task_runner, scoped_refptr caller_task_runner, scoped_refptr io_task_runner, scoped_refptr video_capture_task_runner, base::WeakPtr client_session_control, base::WeakPtr desktop_session_connector, bool virtual_terminal) : audio_capture_task_runner_(audio_capture_task_runner), caller_task_runner_(caller_task_runner), io_task_runner_(io_task_runner), video_capture_task_runner_(video_capture_task_runner), client_session_control_(client_session_control), desktop_session_connector_(desktop_session_connector), desktop_process_(base::kNullProcessHandle), pending_capture_frame_requests_(0), is_desktop_session_connected_(false), virtual_terminal_(virtual_terminal) { DCHECK(caller_task_runner_->BelongsToCurrentThread()); } scoped_ptr DesktopSessionProxy::CreateAudioCapturer() { DCHECK(caller_task_runner_->BelongsToCurrentThread()); return scoped_ptr(new IpcAudioCapturer(this)); } scoped_ptr DesktopSessionProxy::CreateInputInjector() { DCHECK(caller_task_runner_->BelongsToCurrentThread()); return scoped_ptr(new IpcInputInjector(this)); } scoped_ptr DesktopSessionProxy::CreateScreenControls() { DCHECK(caller_task_runner_->BelongsToCurrentThread()); return scoped_ptr(new IpcScreenControls(this)); } scoped_ptr DesktopSessionProxy::CreateVideoCapturer() { DCHECK(caller_task_runner_->BelongsToCurrentThread()); return scoped_ptr(new IpcVideoFrameCapturer(this)); } std::string DesktopSessionProxy::GetCapabilities() const { std::string result = kRateLimitResizeRequests; // Ask the client to send its resolution unconditionally. if (virtual_terminal_) result = result + " " + kSendInitialResolution; return result; } 2.7 million people in Ukraine (6%) were reported having a disability in 2014. This number did not include the (reportedly) 1.5% of people with temporary disabilities. In 2014, 35% of people aged 60–70 had some age-related disability. For people aged over 80 years, this number grew to 50%. Ukraine is notoriously "disability unfriendly". For example, in the capital Kyiv only 4% of infrastructure is considered to be "disability friendly". In the 1990s unemployment rates for disabled people rose sharply in Ukraine (and other Eastern European countries) due to economic downfall. In 2021 Ukraine's national railway company Ukrzaliznytsia launched its first disabled-friendly trains with dedicated wheelchair space. Ukraine is one of the most successful countries of the Paralympic Games. See also Healthcare in Ukraine Health in Ukraine References Human rights in Ukraine Ukraine python lockf and flock behaviour

I have read enough posts on stackoverflow regarding the difference between flock/lockf/fcntl but I am unable to answer the below observation:

>>> import fcntl
>>> a = open('/tmp/locktest', 'w')
>>> b = open('/tmp/locktest', 'w')
>>> fcntl.lockf(a, fcntl.LOCK_EX | fcntl.LOCK_NB)
>>> fcntl.lockf(a, fcntl.LOCK_EX | fcntl.LOCK_NB)
>>> fcntl.lockf(b, fcntl.LOCK_EX | fcntl.LOCK_NB)
>>>
>>> a.close()
>>> b.close()

>>> a = open('/tmp/locktest', 'w')
>>> b = open('/tmp/locktest', 'w')
>>> fcntl.flock(a, fcntl.LOCK_EX | fcntl.LOCK_NB)
>>> fcntl.flock(a, fcntl.LOCK_EX | fcntl.LOCK_NB)
>>> fcntl.flock(b, fcntl.LOCK_EX | fcntl.LOCK_NB)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 35] Resource temporarily unavailable

Why is the behaviour different in the two cases? I know the obvious answer that these are two different locking mechanisms. I am looking for:

  1. What actually lockf() or flock() does to file (inode/fd)?
  2. As per the demo, are we allowed taking the same lock recursively?

I understand the basics of fds and stuff so I would prefer to have a technical answer with more insights to operating system level details.

OSX 10.9.3, Python: 2.7.5

Gentle Confrontation is the fifth album by London-based electronic musician Loraine James, released on 22 September 2023 through Hyperdub. It was produced by James and received acclaim from critics. Critical reception Gentle Confrontation received a score of 84 out of 100 on review aggregator Metacritic based on four critics' reviews, indicating "universal acclaim". Uncut called the album "a varied, disjointed, entirely unpredictable yet utterly singular record", and Mojo felt that "it's the emotional, cathartic journey of the chief protagonist that captivates the most". Pitchforks Christine Kakaire wrote that James "uses chaotic arrangements and glitchy drums to express knotty, difficult-to-name emotions" on the album, which "sprawls, and each track settles into a distinct tonality". The Wire called the tracks "vignettes of memory and emotion, which see her thoughtful production informed by IDM, glitch and electronic emo. True to the album's concept, there's a charming bedroom maximalism" and concluded that it is a "lovely, affecting record". Patrick Gamble of The Skinny found that the "most interesting moments are those where James' voice takes centre stage" as she "take a scalpel blade to her discography, only to reassemble the pieces into a record that plays like a victory lap". Track listing References 2023 albums Albums produced by Loraine James Hyperdub albums Loraine James albums use crate::{ component::{ComponentId, ComponentInfo, ComponentTicks, Components}, entity::Entity, storage::{BlobVec, SparseSet}, }; use bevy_utils::{AHasher, HashMap}; use std::{ cell::UnsafeCell, hash::{Hash, Hasher}, ops::{Index, IndexMut}, ptr::NonNull, }; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct TableId(usize); impl TableId { #[inline] pub fn new(index: usize) -> Self { TableId(index) } #[inline] pub fn index(self) -> usize { self.0 } #[inline] pub const fn empty() -> TableId { TableId(0) } } pub struct Column { pub(crate) component_id: ComponentId, pub(crate) data: BlobVec, pub(crate) ticks: Vec>, } impl Column { #[inline] pub fn with_capacity(component_info: &ComponentInfo, capacity: usize) -> Self { Column { component_id: component_info.id(), data: BlobVec::new(component_info.layout(), component_info.drop(), capacity), ticks: Vec::with_capacity(capacity), } } /// Writes component data to the column at given row. /// Assumes the slot is uninitialized, drop is not called. /// To overwrite existing initialized value, use `replace` instead. /// /// # Safety /// Assumes data has already been allocated for the given row. #[inline] pub unsafe fn initialize(&mut self, row: usize, data: *mut u8, ticks: ComponentTicks) { debug_assert!(row < self.len()); self.data.initialize_unchecked(row, data); *self.ticks.get_unchecked_mut(row).get_mut() = ticks; } /// Writes component data to the column at given row. /// Assumes the slot is initialized, calls drop. /// /// # Safety /// Assumes data has already been allocated for the given row. #[inline] pub unsafe fn replace(&mut self, row: usize, data: *mut u8, change_tick: u32) { debug_assert!(row < self.len()); self.data.replace_unchecked(row, data); self.ticks .get_unchecked_mut(row) .get_mut() .set_changed(change_tick); } /// # Safety /// Assumes data has already been allocated for the given row. #[inline] pub unsafe fn initialize_data(&mut self, row: usize, data: *mut u8) { debug_assert!(row < self.len()); self.data.initialize_unchecked(row, data); } #[inline] pub fn len(&self) -> usize { self.data.len() } #[inline] pub fn is_empty(&self) -> bool { self.data.is_empty() } /// # Safety /// index must be in-bounds #[inline] pub unsafe fn get_ticks_unchecked_mut(&mut self, row: usize) -> &mut ComponentTicks { debug_assert!(row < self.len()); self.ticks.get_unchecked_mut(row).get_mut() } # Copyright 2017 Bruno Ribeiro, Mayank Kakodkar, Pedro Savarese # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import torch from bean.phase import Phase def parse_top_level_arguments(): parser = argparse.ArgumentParser(description='Fit RBM to MNIST using different gradient estimators') parser.add_argument('--local', '-l', dest='LOCAL', action='store_const', const=True, default=False, help='Enables Local run') parser.add_argument('--basefolder', '-b', dest='BASE_FOLDER', action='store' , default='/Users/mkakodka/Code/Research/RBM_V1/', help='Base Folder for all directory paths') parser.add_argument('--phase', '-p', dest='PHASE', action='store' , default='DATA', help=str(Phase.__dict__)) parser.add_argument('-n', dest='RUNS', action='store' , default='1', help='Number of runs') parser.add_argument('-iteration', dest='iteration', action='store' , default='-1', help='iteration') parser.add_argument('--method', '-m', dest='method', action='store', default="MCLV", help='Method to use') parser.add_argument('-sfs', dest='sample_from_supernode', action='store_const', const=True, default=False, help='Sample from supernode for tour distribution') parser.add_argument('-cdk', dest='cdk', action='store', default=1, help='contrastive divergence steps limit') parser.add_argument('-mclvk', dest='mclvk', action='store', default=1, help='tour length limit') parser.add_argument('-wm', dest='warmup', action='store', default=2, help='warmup epochs') parser.add_argument('-tot', '--total-epochs', dest='total_epochs', action='store', default=100, help='total epochs') parser.add_argument('-mbs', '--mini-batch-size', dest='mini_batch_size', action='store', default=128, help='mini batch size') parser.add_argument('--learning-rate', '-lr', dest='learning_rate', action='store', default=0.1, help='learni Cronius (; fl. 2nd century AD) was a celebrated Neopythagorean philosopher. He was probably a contemporary of Numenius of Apamea, who lived in the 2nd century, and he is often spoken of along with him. Nemesius mentions a work of his On Reincarnation, (), and Origen is said to have diligently studied the works of Cronius. Porphyry also states that he endeavoured to explain the fables of the Homeric poems in a philosophical manner. This is all we know about Cronius, although he appears to have been very distinguished among the Neopythagoreans. Notes External links Life of Plotinus by Porphyry 2nd-century Greek philosophers Neo-Pythagoreans var buscar = document.querySelector("#buscar-paciente"); buscar.addEventListener("click", function(){ let xhr = new XMLHttpRequest(); xhr.open("GET","http://api-pacientes.herokuapp.com/pacientes"); xhr.addEventListener("load", function(){ let erroAjax = document.querySelector("#erro-requisicao"); if(xhr.status == 200){ let resposta = xhr.responseText; let pacientes = JSON.parse(resposta); pacientes.forEach(function(paciente){ adicionarTrNaTabela(paciente); }); erroAjax.classList.add("invisivel"); }else{ erroAjax.textContent = "Erro ao buscar paciente"; erroAjax.classList.remove("invisivel"); } }); xhr.send(); }); """This module contains the general information for EquipmentHealthLed ManagedObject.""" from ...ucsmo import ManagedObject from ...ucscoremeta import MoPropertyMeta, MoMeta from ...ucsmeta import VersionMeta class EquipmentHealthLedConsts: COLOR_AMBER = "amber" COLOR_BLUE = "blue" COLOR_GREEN = "green" COLOR_RED = "red" COLOR_UNKNOWN = "unknown" HEALTH_LED_STATE_CRITICAL = "critical" HEALTH_LED_STATE_MINOR = "minor" HEALTH_LED_STATE_NORMAL = "normal" OPER_STATE_BLINKING = "blinking" OPER_STATE_ETH = "eth" OPER_STATE_FC = "fc" OPER_STATE_OFF = "off" OPER_STATE_ON = "on" OPER_STATE_UNKNOWN = "unknown" OPER_STATE_UNSUPPORTED = "unsupported" class EquipmentHealthLed(ManagedObject): """This is EquipmentHealthLed class.""" consts = EquipmentHealthLedConsts() naming_props = set([]) mo_meta = MoMeta("EquipmentHealthLed", "equipmentHealthLed", "health-led", VersionMeta.Version212a, "InputOutput", 0x7f, [], ["admin", "pn-equipment", "pn-maintenance", "pn-policy"], [u'computeBlade', u'computeExtBoard', u'computeRackUnit', u'computeServerUnit', u'equipmentChassis', u'equipmentFanModule', u'equipmentFex', u'equipmentIOCard', u'equipmentPsu'], [u'computeHealthLedSensorAlarm', u'faultInst'], ["Get"]) import React from 'react'; import { connect } from 'react-redux'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faArrowsAlt } from '@fortawesome/free-solid-svg-icons'; import { RootState } from 'src/model/types'; import { zoomOnClick, zoomToggleAction } from 'src/model/actions/datarun'; import { getZoomMode } from 'src/model/selectors/datarun'; import { getIsEditingEventRange } from 'src/model/selectors/events'; type StateProps = ReturnType; type DispatchProps = ReturnType; type ZoomControlsProps = StateProps & DispatchProps; export const ZoomControls: React.FC = (props) => (
); const mapState = (state: RootState) => ({ isZoomEnabled: getZoomMode(state), isEditingEventRange: getIsEditingEventRange(state), }); const mapDispatch = (dispatch: Function) => ({ zoom: (direction) => dispatch(zoomOnClick(direction)), zoomToggle: (mode) => dispatch(zoomToggleAction(mode)), }); export default connect(mapState, mapDispatch)(ZoomControls); Cheiranthera is a genus of ten species of flowering plants in the family Pittosporaceae and are all endemic to Australia. The following is a list of species accepted by the Australian Plant Census as at April 2020: Cheiranthera alternifolia E.M.Benn. – S.A., (presumed extinct in Vic.) Cheiranthera borealis (E.M.Benn.) L.Cayzer & Crisp – Qld., N.S.W. Cheiranthera brevifolia F.Muell. – W.A. Cheiranthera filifolia Turcz. – W.A. Cheiranthera linearis A.Cunn. ex Lindl. – N.S.W., A.C.T., Vic. Cheiranthera parviflora Benth. – W.A. Cheiranthera preissiana Putt. – W.A. Cheiranthera simplicifolia (E.M.Benn.) L.Cayzer & Crisp – W.A. Cheiranthera telfordii L.Cayzer & Crisp – N.S.W. Cheiranthera volubilis Benth. – S.A. References Pittosporaceae Apiales genera Apiales of Australia Taxa named by Allan Cunningham (botanist) import setuptools import os own_dir = os.path.abspath(os.path.dirname(__file__)) def requirements(): with open(os.path.join(own_dir, 'requirements.oci.txt')) as f: for line in f.readlines(): line = line.strip() if not line or line.startswith('#'): continue yield line def modules(): return [ ] def version(): with open(os.path.join(own_dir, 'VERSION')) as f: return f.read().strip() setuptools.setup( name='gardener-oci', version=version(), description='gardener OCI lib', python_requires='>=3.9.*', py_modules=modules(), packages=['oci'], package_data={ 'ci':['version'], }, install_requires=list(requirements()), entry_points={ }, ) Why is 'present as popover' segue covering the whole screen?

In my project I have a button on the bottom right side of the screen and i added another uiviewcontroller to the storyboard, did control-drag to the uiviewcontroller I wanted as the popover, then set that viewcontroller size to (300, 300) and checked 'use preferred explicit size'. When I load the app and click the button, the entire screen gets covered by the "popover". I also tried to go into the popoverViewController's .m file and set the size but that didn't work either.
Any ideas?

Edit: Since it looks like I have to have it be full screen that is fine however I am still running into some other problems I was having earlier. My popup screen will come up and I make the background black and alpha as .5 to make it see through however it'll do the animation, then once the animation is finished the screen will go from .5 opacity to completely black and the only thing I can see is the battery icon thing.

/******************************************************************************* * Copyright 2017 CPqD. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package br.com.cpqd.asr.recognizer; import java.io.IOException; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.LineEvent; import javax.sound.sampled.LineListener; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.Mixer; import javax.sound.sampled.TargetDataLine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Audio source implementation for a Java microphone dataline input. * */ public class MicAudioSource implements AudioSource, LineListener { private static Logger logger = LoggerFactory.getLogger(MicAudioSource.class.getName()); /** the audio format. */ private AudioFormat af; private TargetDataLine line; private boolean stopped; private boolean started; public MicAudioSource() throws LineUnavailableException { this(new AudioFormat(8000F, 16, 1, true, false)); } public MicAudioSource(AudioFormat format) throws LineUnavailableException { this(format, null); } public MicAudioSource(AudioFormat format, Mixer.Info info) throws LineUnavailableException { if (info != null) { line = AudioSystem.getTargetDataLine(format, info); } else { line = AudioSystem.getTargetDataLine(format); } this.af = format; line.addLineListener(this); } @Override public String getContentType() { return AudioSource.AUDIO_TYPE_RAW; } /** * Obtains the size of the buffer from which data can be read. Note that the * units used are bytes, but will always correspond to an integral number of * sample frames of audio data. * * @return the size of the buffer in bytes */ public int getBufferSize() { return line.getBufferSize(); } SET DEFINE OFF; CREATE TABLE AFW_17_COMPT_TWILI ( SEQNC NUMBER(10), CODE VARCHAR2(23 BYTE), NOM VARCHAR2(60 BYTE), DESCR VARCHAR2(4000 BYTE), ACOUN_ID VARCHAR2(100 BYTE), AUTHE_TOKEN VARCHAR2(100 BYTE), REPRT_WALT VARCHAR2(500 BYTE), MOT_PASSE_WALT VARCHAR2(30 BYTE), DATE_CREAT DATE, UTILS_CREAT VARCHAR2(123 BYTE), DATE_MODFC DATE, UTILS_MODFC VARCHAR2(123 BYTE), NUMR NUMBER(11), INDIC_PARTG VARCHAR2(1 BYTE) DEFAULT 'N', REF_DOMN NUMBER(10), DNR_REF_DOMN NUMBER(10) ) LOGGING NOCOMPRESS NOCACHE MONITORING / import * as TypeGraphQL from "type-graphql"; import * as GraphQLScalars from "graphql-scalars"; import { Prisma } from "@prisma/client"; import { DecimalJSScalar } from "../../scalars"; import { NotificationUpdateWithoutUserInput } from "../inputs/NotificationUpdateWithoutUserInput"; import { NotificationWhereUniqueInput } from "../inputs/NotificationWhereUniqueInput"; @TypeGraphQL.InputType({ isAbstract: true }) export class NotificationUpdateWithWhereUniqueWithoutUserInput { @TypeGraphQL.Field(_type => NotificationWhereUniqueInput, { nullable: false }) where!: NotificationWhereUniqueInput; @TypeGraphQL.Field(_type => NotificationUpdateWithoutUserInput, { nullable: false }) data!: NotificationUpdateWithoutUserInput; } /** * Reads data from the audio source input buffer. This method blocks until * the requested amount of data, specified by the length of the buffer * array, has been read. The number of bytes to be read must represent an * integral number of sample frames, such that: [ bytes read ] % [frame size * in bytes ] == 0 */ @Override public int read(byte[] b) throws IOException, NullPointerException { // se eh a primeira leitura, abre o microfone if (!started) { try { line.open(this.af); } catch (LineUnavailableException e) { throw new IOException("Failure to read audio from microphone", e); } line.start(); } // se o microfone nao foi fechado, faz a leitura if (!stopped) { int nBytesToRead = b.length; // ajusta a quantidade de bytes da leitura, se o tamanho do buffer // nao for multiplo do tamanho do frame int excessBytesInBufferLength = b.length % af.getFrameSize(); if (excessBytesInBufferLength != 0) { // subtrai a sobra do tamanho da leitura nBytesToRead -= excessBytesInBufferLength; } return line.read(b, 0, nBytesToRead); } else { return -1; } } @Override public void close() throws IOException { line.close(); } @Override public void finish() throws IOException { if (line.isActive()) { line.stop(); line.flush(); } } @Override public void update(LineEvent event) { logger.debug("line event [{}]: {}", event.getType(), event.getSource()); if (event.getType().equals(LineEvent.Type.OPEN)) { // when mic is opened reset control flags started = false; stopped = false; } else if (event.getType().equals(LineEvent.Type.START)) { // mic recording started started = true; } else if (event.getType().equals(LineEvent.Type.STOP)) { // mic recording stopped stopped = true; } else if (event.getType().equals(LineEvent.Type.CLOSE)) { } } } $("#formEspecialidades").submit(function (event) { event.preventDefault(); //prevent default action if ((!nombre == "")) { $.ajax( { dataType: "html", type: "POST", url: dir + "/especialidades/crear", // ruta donde se encuentra nuestro action que procesa la peticion XmlHttpRequest data: "nombre=" + nombre + "&alias="+alias+"&piso=" + piso + "&color=" + color, //Se añade el parametro de busqueda del medico beforeSend: function (data) { $("#data_Table").html("Procesando..."); }, success: function (requestData) {//armar la tabla const Toast = Swal.mixin({ toast: true, position: 'top-end', showConfirmButton: false, timer: 3000, onOpen: (toast) => { toast.addEventListener('mouseenter', Swal.stopTimer) toast.addEventListener('mouseleave', Swal.resumeTimer) } }); Toast.fire({ icon: 'success', title: 'Dato creado correctamente!' }); $('#formModal').modal('hide'); $("#data_Table").html(requestData); toDataTable("#dataTableEspecialidad"); nombre = ''; }, error: function (requestData, strError, strTipoError) { }, complete: function (requestData, exito) { //fin de la llamada ajax. } }); } }); } /** * ActualizarEspecialidad() * * Envia valores del formulario a la accion editar * ! envio mediante POST ajax * @param dir directorio del proyecto * @param id id de la especialidad a editar * @param piso piso_id de la especialidad a editar * @param nombre nombre de la especialidad a editar */ function ActualizarEspecialidad() { var id = $("#especialidad_id").val(); var piso = $("#comboPiso").val(); var nombre = $("#nombre_especialidad").val(); var alias = $("#alias_especialidad").val(); /// import { EnhancedEventEmitter } from './EnhancedEventEmitter'; import { Channel } from './Channel'; import { PayloadChannel } from './PayloadChannel'; import { MediaKind, RtpParameters } from './RtpParameters'; export declare type ProducerOptions = { /** * Producer id (just for Router.pipeToRouter() method). */ id?: string; /** * Media kind ('audio' or 'video'). */ kind: MediaKind; /** * RTP parameters defining what the endpoint is sending. */ rtpParameters: RtpParameters; /** * Whether the producer must start in paused mode. Default false. */ paused?: boolean; /** * Just for video. Time (in ms) before asking the sender for a new key frame * after having asked a previous one. Default 0. */ keyFrameRequestDelay?: number; /** * Custom application data. */ appData?: any; }; /** * Valid types for 'trace' event. */ export declare type ProducerTraceEventType = 'rtp' | 'keyframe' | 'nack' | 'pli' | 'fir'; /** * 'trace' event data. */ export declare type ProducerTraceEventData = { /** * Trace type. */ type: ProducerTraceEventType; /** * Event timestamp. */ timestamp: number; /** * Event direction. */ direction: 'in' | 'out'; /** * Per type information. */ info: any; }; export declare type ProducerScore = { /** * SSRC of the RTP stream. */ ssrc: number; /** * RID of the RTP stream. */ rid?: string; /** * The score of the RTP stream. */ score: number; }; export declare type ProducerVideoOrientation = { /** * Whether the source is a video camera. */ camera: boolean; /** * Whether the video source is flipped. */ flip: boolean; /** * Rotation degrees (0, 90, 180 or 270). */ rotation: number; }; export declare type ProducerStat = { type: string; timestamp: number; ssrc: number; rtxSsrc?: number; rid?: string; kind: string; mimeType: string; packetsLost: number; fractionLost: number; packetsDiscarded: number; packetsRetransmitted: number; packetsRepaired: number; nackCount: number; nackPacketCount: number; pliCount: number; firCount: number; score: number; packetCount: number; byteCount: number; bitrate: number; roundTripTime?: number; rtxPacketsDiscarded?: number; jitter: number; bitrateByLayer?: any; }; /** * Producer type. */ export declare type ProducerType = 'simple' | 'simulcast' | 'svc'; export declare class Producer extends EnhancedEventEmitter { private readonly _internal; private readonly _data; private readonly _channel; private readonly _payloadChannel; private _closed; private readonly _appData?; private _paused; private _score; private readonly _observer; /** * @private * @emits t HoughCircles circle detection using opencv and python-

I am trying to use OpenCV's (Hough)Circle detection to.. detect circles. I created a solid circle on a black background, tried to play with the parameters, used blur and everything, but I am just not able to make it find anything.

Any ideas, suggestions etc. would be great, thank you!

my current code is something like this:

import cv2
import numpy as np

"""
params = dict(dp=1,
              minDist=1,
              circles=None,
              param1=300,
              param2=290,
              minRadius=1,
              maxRadius=100)
"""

img = np.ones((200,250,3), dtype=np.uint8)
for i in range(50, 80, 1):
    for j in range(40, 70, 1):
        img[i][j]*=200

cv2.circle(img, (120,120), 20, (100,200,80), -1)


gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
canny = cv2.Canny(gray, 200, 300)

cv2.imshow('shjkgdh', canny)
gray = cv2.medianBlur(gray, 5)
circles = cv2.HoughCircles(gray, cv2.cv.CV_HOUGH_GRADIENT, 1, 20,
              param1=100,
              param2=30,
              minRadius=0,
              maxRadius=0)

print circles
circles = np.uint16(np.around(circles))
for i in circles[0,:]:
    cv2.circle(img,(i[0],i[1]),i[2],(0,255,0),2)
    cv2.circle(img,(i[0],i[1]),2,(0,0,255),3)

cv2.imshow('circles', img)
k = cv2.waitKey(0)
if k == 27:
    cv2.destroyAllWindows()
from datetime import datetime from typing import Any, List, Union import pytest from neuro_sdk import BlobCommonPrefix, BlobObject, Bucket, BucketEntry from neuro_cli.formatters.blob_storage import ( BaseBlobFormatter, LongBlobFormatter, SimpleBlobFormatter, ) class TestBlobFormatter: buckets: List[Bucket] = [ Bucket( id="bucket-1", name="neuro-my-bucket", created_at=datetime(2018, 1, 1, 3), cluster_name="test-cluster", owner="test-user", provider=Bucket.Provider.AWS, imported=False, ), Bucket( id="bucket-2", name="neuro-public-bucket", created_at=datetime(2018, 1, 1, 17, 2, 4), cluster_name="test-cluster", owner="public", provider=Bucket.Provider.AWS, imported=False, ), Bucket( id="bucket-3", name="neuro-shared-bucket", created_at=datetime(2018, 1, 1, 13, 1, 5), cluster_name="test-cluster", owner="another-user", provider=Bucket.Provider.AWS, imported=False, ), ] blobs: List[BucketEntry] = [ BlobObject( key="file1024.txt", modified_at=datetime(2018, 1, 1, 14, 0, 0), bucket=buckets[0], size=1024, ), BlobObject( key="file_bigger.txt", modified_at=datetime(2018, 1, 1, 14, 0, 0), bucket=buckets[1], size=1_024_001, ), BlobObject( key="folder2/info.txt", modified_at=datetime(2018, 1, 1, 14, 0, 0), bucket=buckets[2], size=240, ), BlobObject( key="folder2/", modified_at=datetime(2018, 1, 1, 14, 0, 0), bucket=buckets[2], size=0, ), ] folders: List[BucketEntry] = [ BlobCommonPrefix(bucket=buckets[0], key="folder1/", size=0), BlobCommonPrefix(bucket=buckets[1], key="folder2/", size=0), ] all: List[Union[Bucket, BucketEntry]] = [*buckets, *blobs, *folders] @pytest.mark.parametrize( "formatter", [ (SimpleBlobFormatter(color=False, uri_formatter=str)), (LongBlobFormatter(human_readable=False, color=False, uri_formatter=str)), ], ) def test_long_formatter(self, rich_cmp: Any, formatter: BaseBlobFormatter) -> None: for index, item in enumerate(self.all): rich_cmp(formatter(item), index=index) To supply larger populations Gadara, and the neighbouring Decapolis cities of Adraa (Dera'a, Syria) and Abila (Qweilbeh, Jordan) undertook construction of a water supply system of 170 km of aqueduct tunnels connecting the cities to springs throughout southern Syria and an artificially constructed lake at Dille. Constructed between 90 - 210 CE the network of rock cut tunnels included 2,900 access shafts, and a single 106km section represents one of the most significant hydro-engineering accomplishments of the ancient world. During the Severan period (193 – 235CE) the city underwent a rapid expansion westwards and many of the large civic monuments still visible on the site today date to this period and attest to an increase in importance and prosperity. After the Christianisation of the Eastern Roman Empire, Gadara retained its important regional status and became for many years the seat of a Christian bishop. Early Islamic period The Battle of Yarmouk in 636 CE a short distance from Gadara, brought the entire region under Arab-Muslim rule. On 18th January 749 CE much of the city was destroyed by the Galilee earthquake. Whilst the city was extensively damaged, archaeological evidence of limited reconstruction, including conversion of the large five aisle basilica church into a mosque indicates the continued settlement of the site at least into the 11th Century. By the 13th Century the site is noted in historic sources under the new name of "Mukais" a local term meaning border place or customs house and from which the modern name of Umm Qais gradual derived. Ottoman period In 1596 it appeared in the Ottoman tax registers named as Mkeis, situated in the nahiya (subdistrict) of Bani Kinana, part of the Sanjak of Hawran. It had 21 households and 15 bachelors; all Muslim, in addition to 3 Christian households. The villagers paid a fixed tax-rate of 25% on agricultural products; including wheat, barley, summer crops, fruit trees, goats and bee-hives. The total tax was 8,500 akçe. In 1806 Ulrich Jasper Seetzen visited Umm Qais and identified it as the location of ancient Gadara, describing the Ottoman settlement and the tombs and other monuments still visible on the surface. The ancient ruins at Um Keis were recorded again by western visitors in 1816 and 1838. By 1899 Schumacher, visiting the site as part of his survey work for the Hijaz railway records the village had expanded significantly with the construction of larger houses, noting also that many of the tombs recorded by early visitors were no longer present. Umm Qais's most impressive building, the Ottoman governor's residence known as Beit Rousan, "Rousan House", dates to this period of expansion in the Late Ottoman period. {/* Button colors */}
Pick your color
Outline
{/* Button links */}
Links
{{value}} ` }) export class CallsCellRenderer implements ICellRenderer { private params: any; private value: number; agInit(params: any): void { this.params = params; this.value = params.value; } onAdd(): void { var oldData = this.params.node.data; var oldCallRecords = oldData.callRecords; var newCallRecords = oldCallRecords.slice(0); // make a copy newCallRecords.push({ name: ["Bob","Paul","David","John"][Math.floor(Math.random()*4)], callId: Math.floor(Math.random()*1000), duration: Math.floor(Math.random()*100) + 1, switchCode: "SW5", direction: "Out", number: "(02) " + Math.floor(Math.random()*1000000) }); // add one item var minutes = 0; newCallRecords.forEach( (r: any) => minutes += r.duration ); var newData = { name: oldData.name, account: oldData.account, calls: newCallRecords.length, minutes: minutes, callRecords: newCallRecords }; this.params.api.applyTransaction({update: [newData]}); this.params.node.setExpanded(true); } onRemove(): void { var oldData = this.params.node.data; var oldCallRecords = oldData.callRecords; if (oldCallRecords.length==0) { return; } var newCallRecords = oldCallRecords.slice(0); // make a copy newCallRecords.pop(); // remove one item var minutes = 0; newCallRecords.forEach( (r:any) => minutes += r.duration ); var newData = { name: oldData.name, account: oldData.account, calls: newCallRecords.length, minutes: minutes, callRecords: newCallRecords }; this.params.api.applyTransaction({update: [newData]}); } } // Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package text import ( "bytes" "fmt" "math" "strconv" "strings" "github.com/schattian/protobuf/internal/flags" ) // Kind represents a token kind expressible in the textproto format. type Kind uint8 // Kind values. const ( Invalid Kind = iota EOF Name // Name indicates the field name. Scalar // Scalar are scalar values, e.g. "string", 47, ENUM_LITERAL, true. MessageOpen MessageClose ListOpen ListClose // comma and semi-colon are only for parsing in between values and should not be exposed. comma semicolon // bof indicates beginning of file, which is the default token // kind at the beginning of parsing. bof = Invalid ) func (t Kind) String() string { switch t { case Invalid: return "" case EOF: return "eof" case Scalar: return "scalar" case Name: return "name" case MessageOpen: return "{" case MessageClose: return "}" case ListOpen: return "[" case ListClose: return "]" case comma: return "," case semicolon: return ";" default: return fmt.Sprintf("", uint8(t)) } } // NameKind represents different types of field names. type NameKind uint8 // NameKind values. const ( IdentName NameKind = iota + 1 TypeName FieldNumber ) func (t NameKind) String() string { switch t { case IdentName: return "IdentName" case TypeName: return "TypeName" case FieldNumber: return "FieldNumber" default: return fmt.Sprintf("", uint8(t)) } } // Bit mask in Token.attrs to indicate if a Name token is followed by the // separator char ':'. The field name separator char is optional for message // field or repeated message field, but required for all other types. Decoder // simply indicates whether a Name token is followed by separator or not. It is // up to the prototext package to validate. const hasSeparator = 1 << 7 // Scalar value types. const ( numberValue = iota + 1 stringValue literalValue ) // Bit mask in Token.numAttrs to indicate that the number is a negative. const isNegative = 1 << 7 import React, { useState } from 'react' import useForm from '../Functions/UseForm' import FormRenderer from './FormRenderer'; import { Col, FormGroup, Input, Label, Row, Modal, ModalHeader, ModalBody, ModalFooter, Alert } from 'reactstrap'; import { ToastContainer, toast } from 'react-toastify' import 'react-toastify/dist/ReactToastify.css' import MatButton from '@material-ui/core/Button' import * as actions from "../../actions/patients"; import { connect } from 'react-redux' const FormRendererModal = (props ) => { const [errorMsg, setErrorMsg] = useState('') const [showErrorMsg, setShowErrorMsg] = useState(false) const [loading, setLoading] = useState(false) const onDismiss = () => setShowErrorMsg(false) const toggle = () => { return props.setShowModal(!props.showModal) } return ( {props.title || ''} {errorMsg} ); } const mapStateToProps = state => { return { patient: state.patients.patient } } const mapActionToProps = { } export default connect(mapStateToProps, mapActionToProps)(FormRendererModal) Uten sko (2011) Livet er for kjipt (2011) Er så lei (2012), with Johnny Gellein …og det var langt på natt (2012) En natt til (2012) Bare vent (2012) Oh My Mind (Toby & Helfner Metal Remix) (2012) Frøken Möet (Trekant) (2012) Russ 2013 (du er deilig, du er spretten) (2013) Kaptein Morgan (2013), with Jesper Borgen Kings of Asia (2013), with Kings of Asia Metal Sessions (2013) Haldens nummer 9 (Trollmannen fra Os) (2013), with Bingobanden Se så glad nissen er (2013) Brun og blid (TIX Remix) (2014), with Katastrofe & M.M.B Ballongmannen (2014), with Ballongmannen and Morgan Sulele Brun og blid (Disco Jumperz Remix) (2014) Et drikkehjem (2014), with Martin Tungevaag Russ 2014 (du er født i '95) (2014) Min skyld (2014), with Ole I'Dole 18 Wiener (2014), with Katastrofe En godt stekt pizza (2015), with Katastrofe 20 kilo ekstra (2015), with Torgeir and Kjendisene Skilles Johanne (2015) Lærerinna (2015), with Innertier Alle gutta (2015) Hjem til deg (2015) En sinnsykt godt stekt pizza (2016) Her er rompa mi (2016) Frågan (2016, under the name Lasse Stianz) En siste gang (2017) KJØRR (2017), with Klish Muggene er megasvære (elsker øl) (2017), with DJ Anton Om 100 år er allting glemt (2017), with Lothepus Kyss meg (2018) Participating in Lars Corleone ft. Howard: Uten sko (2014) Sony Music Entertainment: Kule Kidz – Stjernemix 1 (2014) Morgan Sulele: Morgans kleineste (2015) ESS Engros: Livets glade gutter 2 – 19 norske festfavoritter (2015) Sony Music Entertainment: Julebord 2015 (2015) Torgeir & Kjendisene: En runde til (2016) Elov & Beny: Kör (2017) Sony Music Entertainment: Raggarbilshits Vol. 3: Raggaerrock & Rockabilly (2018) Bibliography How to become a norsk superkjendis (English: How to become a Norwegian superstar) (2016) References External links Norwegian actors People from Fredrikstad Norwegian songwriters 1982 births Living people Heartland Championship Team 2015 Steelform Wanganui Heartland extended squad Forwards: Brett Turner (Pirates); Bryn Hudson (Ngamatapouri); Cole Baldwin (Border); Daniel Fitzgerald (Marist); Fraser Hammond (Ruapehu); Kamipeli Latu (Border); Kieran Hussey (Border); Lasa Ulukuta (Pirates); Malakai Volau (Utiku OB); Peter Rowe (Ruapehu)(Captain); Renato Tikoilosomone (Border); Roman Tutauha (Ruapehu); Sam Madams (Border); Tololi Moala (Pirates); Viki Tofa (Marist). * John Smyth Brought in as injury cover. Backs: Areta Lama (Kaierau); Ace Malo (Kaierau); Denning Tyrell (Pirates); Jaye Flaws (Taihape); Kane Tamou (Ratana); Lindsay Horrocks (Border); Michael Nabuliwaqe (Utiku OB); Poasa Waqanibau (Border); Samu Kubunavanua (Utiku OB); Simon Dibben (Marist); Stephen Pereofeta (Wanganui Collegiate); Troy Brown (Ruapehu); William Short (Ruapehu); Zyon Hekenui (Ruapehu); Trinity Spooner-Neera (Hawkes Bay) Ranfurly Shield Matches Wanganui v Taranaki challenge of 1964 A 15-all draw against the powerful Taranaki side of 1964 remains the closest the men from Wanganui have ever come to winning the Ranfurly Shield. Into the last minutes of the match Wanganui held a 12–11 lead and even if on paper and in the match itself they had seemed the inferior team it seemed as if they would hang on. Their hero was wing Colin Pierce who had kicked all of Wanganui's points from penalties to put them ahead even though Taranaki had gained tries to John McCullough and Ross Brown. Wanganui might well have won as the match approached the final minute but for excitement of their supporters who thinking they were part of a historic moment as Wanganui had never won the Ranfurly Shield crowded the touchline. A desperate Brown had dropped for goal trying to gain the winning points. When it had missed Pierce had dashed to the 22 and taken a quick drop out. In the event his hurried kick had landed among the Wanganui spectators and they gave referee John Pring and touch judge George Brightwell a dilemma for they were both unsighted by the sideline mayhem were not sure whether the ball had bounced or gone out on a full. Pring ruled that it had been on the full and so that last scrum of the match in what was the last set-piece took place on the Wanganui 22 and it was from there that Taranaki worked the move from which replacement wing Kerry Hurley grubber kicked ahead and won the chase as the ball bounced just a feet from touch over the Wanganui goal-line. And that was it: Taranaki had won 14–12. Wanganui in Super Rugby Wanganui, along with Wellington, Wairarapa Bush, East Coast, Poverty Bay, Hawke's Bay, Manawatu and Horowhenua-Kapiti make up the Hurricanes region. All Blacks There have been 17 players selected for the All Blacks while playing club rugby in Whanganui: return self.HEAD() && !self.inRebase() && !self.inMerge(); }); this.canStashAll = ko.computed(function() { return !self.amend(); }); this.showNux = ko.computed(function() { return self.files().length == 0 && !self.amend() && !self.inRebase() && !self.emptyCommit(); }); this.commitValidationError = ko.computed(function() { if (!self.emptyCommit() && !self.amend() && !self.files().some(function(file) { return file.editState() === 'staged' || file.editState() === 'patched'; })) return "No files to commit"; if (self.files().some(function(file) { return file.conflict(); })) return "Files in conflict"; if (!self.commitMessageTitle() && !self.inRebase()) return "Provide a title"; if (self.textDiffType.value() === 'sidebysidediff') { var patchFiles = self.files().filter(function(file) { return file.editState() === 'patched'; }); if (patchFiles.length > 0) return "Cannot patch with side by side view." } return ""; }); this.toggleSelectAllGlyphClass = ko.computed(function() { if (self.allStageFlag()) return 'glyphicon-unchecked'; else return 'glyphicon-check'; }); rspec failing error: expected false to respond to `false?`

I am running this portion of a test:

 describe Dictionary do
   before do
     @d = Dictionary.new
   end

    it 'can check whether a given keyword exists' do
        @d.include?('fish').should be_false
      end

With this code:

class Dictionary
  def initialize
    @hash = {}
  end 

  def add(new_entry)
    new_entry.class == String ? @hash[new_entry] = nil : new_entry.each { |noun, definition| @hash[noun] = definition}    
  end 

  def entries
    @hash 
  end 

  def keywords
    @hash.keys
  end

  def include?(word)
    if @hash.has_key?(word)
      true
    else 
      false
    end 
  end 
end 

I don't know what I'm doing wrong, but my tests keep failing and saying this:

> 1) Dictionary can check whether a given keyword exists
>      Failure/Error: @d.include?('fish').should be_false
>        expected false to respond to `false?`

I am confused at the error since it seems to be giving the correct answer. I would really appreciate if someone could take a few minutes to tell me what's wrong with my code. Thank you tons.

Context path for web application on Glassfish 3.1.2.2

I'm trying to find a way to explicitly specify the context path of a web application being deployed to Glassfish 3.1.2.2 but I've had no luck so far. Can anyone provide guidance on this? The background to this is below:

I have a web application that consists of two separate Netbeans (7.0) projects. The first is a web service and is called FooWS. The second is a user facing web application which uses the FooWS webservice. It's called FooApp.

I've recently upgraded glassfish to 3.1.2.2 in the hope of resolving some other issue and now when I deploy the FooWS app, it deploys successfully but with the context path /web rather than /FooWS. This is not something I would particularly care about except that when I try to deploy FooApp, glassfish also tries to deploy that to /web leading to the following error:

SEVERE: Exception while loading the app : java.lang.Exception: WEB0113: Virtual server [server] already has a web module [FooWS] loaded at [/web]; therefore web module [FooApp] cannot be loaded at this context path on this virtual server.

The web.xml for FooApp looks as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>defaultWebRootId</param-name>
        <param-value>2631</param-value>
    </context-param>

    <listener>
        <listener-class>com.foo.service.AppInitialiser</listener-class>
    </listener>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

The configuration for FooWS is similar. Neither contains any mention of the application context so my expectation is that it should use /FooWS rather than default to /web.

The obvious solution would seem to be to override the context path in the web.xml but I can't find any way of doing this. Any suggestions?

Just some follow up, I accidentally changed the context path to /FooW. This time it deployed as expected to /FooW. Changing it back if /FooWS causes the old behaviour to return, that is, it deploys again to /web. It seems like I have a workaround for the moment.

For the benefit of anyone following this, I got the same behaviour with 3.1.2. I have now returned to 3.1 (b43) and it behaves as expected.

echo "complete -C '/usr/local/bin/aws_completer' aws" >> /home/ec2-user/.bashrc #mkdir /home/ec2-user/CA mkdir /home/ec2-user/.aws echo '[default]' > /home/ec2-user/.aws/config echo 'output = json' >> /home/ec2-user/.aws/config echo "region = $REGION" >> /home/ec2-user/.aws/config chmod 400 /home/ec2-user/.aws/config chown -R ec2-user:ec2-user /home/ec2-user/.aws IOT_ENDPOINT_OLD=$(aws iot describe-endpoint --region $REGION | jq -r '.endpointAddress') IOT_ENDPOINT=$(aws iot describe-endpoint --region $REGION --endpoint-type iot:Data-ATS | jq -r '.endpointAddress') echo "export IOT_ENDPOINT_OLD=$IOT_ENDPOINT_OLD" >> /home/ec2-user/.bashrc echo "export IOT_ENDPOINT=$IOT_ENDPOINT" >> /home/ec2-user/.bashrc echo 'export PATH=$PATH:/usr/local/bin' >> /home/ec2-user/.bashrc cat /home/ec2-user/banner.txt >> /home/ec2-user/.bashrc rm -f /home/ec2-user/banner.txt test ! -e /home/ec2-user/.ssh && mkdir -m 700 /home/ec2-user/.ssh echo '=== Prepare for Greengrass ===' echo "$(date) === Get repository" >> /tmp/bootstrap.log if ! getent passwd ggc_user; then echo "adding ggc_user" useradd -r ggc_user fi echo "-> ggc_group" if ! getent group ggc_group; then echo "adding ggc_group" groupadd -r ggc_group fi echo "-> hardlink and symlink protection" if [ -e /etc/sysctl.d/00-defaults.conf ]; then if ! grep '^fs.protected_hardlinks\s*=\s*1' /etc/sysctl.d/00-defaults.conf; then echo 'fs.protected_hardlinks = 1' >> /etc/sysctl.d/00-defaults.conf fi if ! grep '^fs.protected_symlinks\s*=\s*1' /etc/sysctl.d/00-defaults.conf; then echo 'fs.protected_symlinks = 1' >> /etc/sysctl.d/00-defaults.conf fi else echo '# AWS Greengrass' >> /etc/sysctl.d/00-defaults.conf echo 'fs.protected_hardlinks = 1' >> /etc/sysctl.d/00-defaults.conf echo 'fs.protected_symlinks = 1' >> /etc/sysctl.d/00-defaults.conf fi sysctl -p sysctl -p /etc/sysctl.d/00-defaults.conf echo '# AWS Greengrass' >> /etc/fstab echo 'cgroup /sys/fs/cgroup cgroup defaults 0 0' >> /etc/fstab mount -a echo '=== Install Greengrass ===' echo "$(date) === Install Greengrass" >> /tmp/bootstrap.log cd /tmp/ wget ${GG_LINK} tar -xzvf ${GG_FILE} -C / cp ggcredentials/cert.pem /greengrass/certs/ cp ggcredentials/private.key /greengrass/certs/ cp ggcredentials/config.json /greengrass/config/ wget -O /greengrass/certs/root.ca.pem https://www.amazontrust.com/repository/AmazonRootCA1.pem echo '=== Prepare Greengrass ML Workshop ===' echo "$(date) === Prepare Greengrass ML Workshop" >> /tmp/bootstrap.log cd /tmp/ cp -R MachineHealthWorkshop/lambdas/PredictionLambda/ /home/ec2-user/environment/ chown -R ec2-user:ec2-user /home/ec2-user/environment/PredictionLambda cp -R MachineHealthWorkshop/lambdas/OPCUALambda/ /home/ec2-user/environment/ chown -R ec2-user:ec2-user /home/ec2-user/environment/OPCUALambda echo '=== Reboot in 1 minute ===' echo "$(date) === Reboot in 1 minute" >> /tmp/bootstrap.log /* * Generated by asn1c-0.9.24 (http://lionet.info/asn1c) * From ASN.1 module "S1AP-PDU" * found in "/home/liu/openairinterface5g/openair3/S1AP/MESSAGES/ASN1/R10.5/S1AP-PDU.asn" * `asn1c -gen-PER` */ #ifndef _S1ap_Paging_H_ #define _S1ap_Paging_H_ #include /* Including external dependencies */ #include #include #include #ifdef __cplusplus extern "C" { #endif /* Forward declarations */ struct S1ap_IE; /* S1ap-Paging */ typedef struct S1ap_Paging { struct S1ap_Paging__s1ap_Paging_ies { A_SEQUENCE_OF(struct S1ap_IE) list; /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } s1ap_Paging_ies; /* * This type is extensible, * possible extensions are below. */ /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } S1ap_Paging_t; /* Implementation */ extern asn_TYPE_descriptor_t asn_DEF_S1ap_Paging; #ifdef __cplusplus } #endif /* Referred external types */ #include "S1ap-IE.h" #endif /* _S1ap_Paging_H_ */ #include template class c++

i try to design a template for my university project. i wrote the follwing code:

#ifndef _LinkedList_H_
#define _LinkedList_H_
#include "Link.h"
#include <ostream>
template <class L>//error one
class LinkedList
{
private:
 Link<L> *pm_head;
 Link<L> * pm_tail;
 int m_numOfElements;
 Link<L>* FindLink(L * dataToFind);
public:
 LinkedList();
 ~LinkedList();
 int GetNumOfElements(){return m_numOfElements;}
 bool Add( L * data);
 L *FindData(L * data);

template <class L> friend ostream & operator<<(ostream& os,const LinkedList<L> listToprint);//error two
   L* GetDataOnTop();
   bool RemoveFromHead();
   L* Remove(L * toRemove);

this templete uses the link class templete

#ifndef _Link_H_
#define _Link_H_
template <class T>//error 3
class Link
{
private:
 T* m_data;
 Link* m_next;
 Link* m_prev;
public:
 Link(T* data);
 ~Link(void);
 bool Link::operator ==(const Link& other)const;

 /*getters*/
 Link* GetNext()const {return m_next;}
 Link* GetPrev()const {return m_prev;}
 T* GetData()const {return m_data;}
 //setters
 void SetNext(Link* next) {m_next = next;}
 void SetPrev(Link* prev) {m_prev = prev;}
 void SetData(T* data) {m_data = data;}

};

error one: shadows template parm `class L'
error two:declaration of `class L'
error three: shadows template parm `class T'

i dont understand what is the problem. i can really use your help thank you :)

Joda Time gives wrong time zone

I'm using the Joda time (1.6) libraries and it keeps returning DateTime objects with the wrong time zone, British Summer Time instead of GMT.

My Windows workstation (running JDK 1.6.0_16) thinks it's in GMT and if I get the default time zone from the JDK date/time classes it is correct (GMT). I get the same behaviour on our Linux servers as well. I thought it could be an error in the time zone database files in Joda so I rebuilt the jar with the latest database but with no change.

import java.util.TimeZone;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;

public class TimeZoneTest {

    public static void main(String[] args) {                
        DateTimeFormatter timeParser = ISODateTimeFormat.timeParser();
        TimeZone timeZone = TimeZone.getDefault();
        System.out.println(timeZone.getID()); // "Europe/London"
        System.out.println(timeZone.getDisplayName()); // "Greenwich Mean Time"

        DateTimeZone defaultTimeZone = DateTimeZone.getDefault();
        System.out.println(defaultTimeZone.getID()); //"Europe/London"
        System.out.println(defaultTimeZone.getName(0L)); //"British Summer Time"

        DateTime currentTime = new DateTime();
        DateTimeZone currentZone = currentTime.getZone();
        System.out.println(currentZone.getID()); //"Europe/London"
        System.out.println(currentZone.getName(0L)); //"British Summer Time"            
    }
}

Debugging through the static initialiser in org.joda.time.DateTimeZone I see that the System.getProperty("user.timezone") call gives "Europe/London" as expected.

// SPDX-License-Identifier: MPL-2.0 // SPDX-FileCopyrightText: 2021 The vanadinite developers // // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at https://mozilla.org/MPL/2.0/. #![allow(clippy::match_bool, clippy::identity_op)] #![allow(incomplete_features)] #![feature( alloc_error_handler, allocator_api, arbitrary_self_types, asm, const_btree_new, const_fn_fn_ptr_basics, const_fn, const_fn_trait_bound, const_generics, destructuring_assignment, extern_types, fn_align, inline_const, maybe_uninit_ref, naked_functions, new_uninit, raw_ref_op, thread_local )] #![no_std] #![no_main] #[cfg(not(target_pointer_width = "64"))] compile_error!("vanadinite assumes a 64-bit pointer size, cannot compile on non-64 bit systems"); extern crate alloc; pub mod asm; pub mod boot; pub mod cpu_local; pub mod csr; pub mod drivers; pub mod interrupts; pub mod io; pub mod mem; pub mod platform; pub mod scheduler; pub mod sync; pub mod syscall; pub mod task; pub mod trap; pub mod utils; use { core::sync::atomic::{AtomicUsize, Ordering}, drivers::{generic::plic::Plic, CompatibleWith}, interrupts::PLIC, mem::{ kernel_patching, paging::{PhysicalAddress, VirtualAddress}, phys::{PhysicalMemoryAllocator, PHYSICAL_MEMORY_ALLOCATOR}, phys2virt, }, sync::SpinMutex, utils::Units, }; use alloc::boxed::Box; use drivers::InterruptServicable; use fdt::Fdt; use mem::kernel_patching::kernel_section_v2p; use sbi::{hart_state_management::hart_start, probe_extension, ExtensionAvailability}; use scheduler::Scheduler; pub use vanadinite_macros::{debug, error, info, trace, warn}; static N_CPUS: AtomicUsize = AtomicUsize::new(1); static TIMER_FREQ: AtomicUsize = AtomicUsize::new(0); static INIT_FS: &[u8] = include_bytes!("../../../initfs.tar"); static BLOCK_DEV: SpinMutex> = SpinMutex::new(None); cpu_local! { static HART_ID: core::cell::Cell = core::cell::Cell::new(0); } #[no_mangle] #[repr(align(4))] extern "C" fn kmain(hart_id: usize, fdt: *const u8) -> ! { csr::stvec::set(trap::stvec_trap_shim); let heap_frame_alloc = unsafe { PHYSICAL_MEMORY_ALLOCATOR.lock().alloc_contiguous(64) }; let heap_start = mem::phys2virt(heap_frame_alloc.expect("moar memory").as_phys_address()); unsafe { mem::heap::HEAP_ALLOCATOR.init(heap_start.as_mut_ptr(), 64 * 4.kib()) }; unsafe { crate::cpu_local::init_thread_locals() }; HART_ID.set(hart_id); crate::io::logging::init_logging(); let fdt: Fdt<'static> = match unsafe { Fdt::from_ptr(fdt) } { Ok(fdt) => fdt, Err(e) => crate::platform::exit(crate::platform::ExitStatus::Error(&e)), }; /* * This header is generated by classdump-dyld 1.0 * on Saturday, June 1, 2019 at 6:46:33 PM Mountain Standard Time * Operating System: Version 12.1.1 (Build 16C5050a) * Image Source: /System/Library/PrivateFrameworks/CompanionSync.framework/CompanionSync * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ #import #import @class NRDevice, NSUUID, NSString, NSDate, PBCodable; @interface SYDevice : NSObject { NRDevice* _nrDevice; NSUUID* _pairingID; NSString* _pairingStorePath; NSString* _deviceClass; NSString* _systemVersion; NSString* _systemBuildVersion; NSDate* _lastActiveDate; BOOL _hasCachedNearby; BOOL _cachedIsNearby; long long _state; } @property (nonatomic,readonly) NRDevice * nrDevice; //@synthesize nrDevice=_nrDevice - In the implementation block @property (assign,nonatomic) long long state; //@synthesize state=_state - In the implementation block @property (getter=isTargetable,nonatomic,readonly) BOOL targetable; @property (getter=isPaired,nonatomic,readonly) BOOL paired; @property (getter=isActive,nonatomic,readonly) BOOL active; @property (nonatomic,copy,readonly) NSString * pairingStorePath; //@synthesize pairingStorePath=_pairingStorePath - In the implementation block @property (nonatomic,readonly) NSUUID * pairingID; //@synthesize pairingID=_pairingID - In the implementation block @property (nonatomic,readonly) long long deviceCode; @property (nonatomic,readonly) NSString * deviceClass; //@synthesize deviceClass=_deviceClass - In the implementation block @property (nonatomic,readonly) NSString * systemVersion; //@synthesize systemVersion=_systemVersion - In the implementation block @property (nonatomic,readonly) NSString * systemBuildVersion; //@synthesize systemBuildVersion=_systemBuildVersion - In the implementation block @property (nonatomic,readonly) NSDate * lastActiveDate; //@synthesize lastActiveDate=_lastActiveDate - In the implementation block @property (nonatomic,readonly) BOOL supportsFileTransferMessageSend; @property (assign,nonatomic) BOOL hasCachedNearby; //@synthesize hasCachedNearby=_hasCachedNearby - In the implementation block @property (assign,nonatomic) BOOL cachedIsNearby; //@synthesize cachedIsNearby=_cachedIsNearby - In the implementation block @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; @property (nonatomic,readonly) PBCodable * stateForLogging; +(id)targetableDevice; +(id)knownDevices; +(id)deviceForNRDevice:(i var SECTION = "15.5.4.8-1"; var VERSION = "ECMA_1"; startTest(); var TITLE = "String.prototype.split"; writeHeaderToLog( SECTION + " "+ TITLE); new TestCase( SECTION, "String.prototype.split.length", 2, String.prototype.split.length ); new TestCase( SECTION, "delete String.prototype.split.length", false, delete String.prototype.split.length ); new TestCase( SECTION, "delete String.prototype.split.length; String.prototype.split.length", 2, eval("delete String.prototype.split.length; String.prototype.split.length") ); // test cases for when split is called with no arguments. // this is a string object new TestCase( SECTION, "var s = new String('this is a string object'); typeof s.split()", "object", eval("var s = new String('this is a string object'); typeof s.split()") ); new TestCase( SECTION, "var s = new String('this is a string object'); Array.prototype.getClass = Object.prototype.toString; (s.split()).getClass()", "[object Array]", eval("var s = new String('this is a string object'); Array.prototype.getClass = Object.prototype.toString; (s.split()).getClass()") ); new TestCase( SECTION, "var s = new String('this is a string object'); s.split().length", 1, eval("var s = new String('this is a string object'); s.split().length") ); new TestCase( SECTION, "var s = new String('this is a string object'); s.split()[0]", "this is a string object", eval("var s = new String('this is a string object'); s.split()[0]") ); // this is an object object new TestCase( SECTION, "var obj = new Object(); obj.split = String.prototype.split; typeof obj.split()", "object", eval("var obj = new Object(); obj.split = String.prototype.split; typeof obj.split()") ); new TestCase( SECTION, "var obj = new Object(); obj.split = String.prototype.split; Array.prototype.getClass = Object.prototype.toString; obj.getClass()", "[object Array]", eval("var obj = new Object(); obj.split = String.prototype.split; Array.prototype.getClass = Object.prototype.toString; obj.split().getClass()") ); new TestCase( SECTION, "var obj = new Object(); obj.split = String.prototype.split; obj.split().length", 1, eval("var obj = new Object(); obj.split = String.prototype.split; obj.split().length") ); new TestCase( SECTION, "var obj = new Object(); obj.split = String.prototype.split; obj.split()[0]", "[object Object]", eval("var obj = new Object(); obj.split = String.prototype.split; obj.split()[0]") ); // this is a function object new TestCase( SECTION, "var obj = new Function(); obj.split = String.prototype.split; typeof obj.split()", "object", eval("var obj = new Function(); obj.split = String.prototype.split; typeof obj.split()") ); -- phpMyAdmin SQL Dump -- version 4.9.0.1 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 28-05-2021 a las 04:22:04 -- Versión del servidor: 10.4.6-MariaDB -- Versión de PHP: 7.3.9 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `inscripcion` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `adulto` -- CREATE TABLE `adulto` ( `id` int(11) NOT NULL, `nombre` varchar(255) NOT NULL, `documento` varchar(50) NOT NULL, `fecha_expedicion` date NOT NULL, `fecha_nacimiento` date NOT NULL, `sexo` varchar(50) NOT NULL, `direccion` varchar(255) DEFAULT NULL, `telefono` varchar(50) NOT NULL, `sisben` varchar(50) DEFAULT NULL, `nombre_contacto` varchar(255) NOT NULL, `telefono_contacto` varchar(50) DEFAULT NULL, `celular_contacto` varchar(50) NOT NULL, `direccion_contacto` varchar(255) DEFAULT NULL, `cedula` varchar(50) DEFAULT NULL, `recibo` varchar(50) NOT NULL, `certificado_postulacion` varchar(50) NOT NULL, `certificado_sisben` varchar(50) NOT NULL, `fecha_creacion` timestamp NOT NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `adulto` -- INSERT INTO `adulto` (`id`, `nombre`, `documento`, `fecha_expedicion`, `fecha_nacimiento`, `sexo`, `direccion`, `telefono`, `sisben`, `nombre_contacto`, `telefono_contacto`, `celular_contacto`, `direccion_contacto`, `cedula`, `recibo`, `certificado_postulacion`, `certificado_sisben`, `fecha_creacion`) VALUES (1, 'Marina', '100', '2021-03-08', '2021-03-09', 'Femenino', 'Blas de Lezo', '300', '32', 'Abelardo', '32432', '3423', 'Calle 70', '100.pdf', '100.png', '100.jpg', '100.png', '2021-03-09 02:04:52'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `control` -- CREATE TABLE `control` ( `id` int(11) NOT NULL, `documento` varchar(50) NOT NULL, `imagen` varchar(50) NOT NULL, `img` varchar(255) NOT NULL, `estado` varchar(50) NOT NULL, `estado_upload` int(11) NOT NULL DEFAULT 1, `observacion` text DEFAULT NULL, `users_id` int(11) NOT NULL, `fecha_creacion` timestamp NOT NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `control` -- ### User: Is it faster to run a million small SQLite inserts one by one or in a single transaction? Why? ### Assistant: A single transaction — faster by orders of magnitude, sometimes hundreds of times. By default SQLite wraps each statement in its own transaction, and every transaction ends with an fsync — a forced flush to disk for durability. A million single inserts = a million fsyncs, and an fsync costs milliseconds even on SSDs. Inside one transaction, fsync happens once at COMMIT. Practically: wrap the batch in `BEGIN ... COMMIT`, use a prepared statement, and enable `PRAGMA journal_mode=WAL` — with WAL, writes don't block readers and commits are cheaper. Linux C++: Linker is outputting strange errors

Alright, here is the output I get:

arm-none-linux-gnueabi-ld --entry=main -dynamic-linker=/system/bin/linker -rpath-link=/home/oem/android-ndk-r3/build/platforms/android-5/arch-arm/usr/lib -L/home/oem/android-ndk-r3/build/platforms/android-5/arch-arm/usr/lib -nostdlib -lstdc++ -lm -lGLESv1_CM -rpath=/home/oem/android-ndk-r3/build/platforms/android-5/arch-arm/usr/lib -rpath=../../YoghurtGum/lib/Android -L./lib/Android intermediate/Alien.o intermediate/Bullet.o intermediate/Game.o intermediate/Player.o ../../YoghurtGum/bin/YoghurtGum.a -o bin/Galaxians.android
intermediate/Game.o: In function `Galaxians::Init()':
/media/YoghurtGum/Tests/Galaxians/src/Game.cpp:45: undefined reference to `__cxa_end_cleanup'
/media/YoghurtGum/Tests/Galaxians/src/Game.cpp:44: undefined reference to `__cxa_end_cleanup'
intermediate/Game.o:(.ARM.extab+0x18): undefined reference to `__gxx_personality_v0'
intermediate/Game.o: In function `Player::Update()':
/media/YoghurtGum/Tests/Galaxians/src/Player.h:41: undefined reference to `__cxa_end_cleanup'
intermediate/Game.o:(.ARM.extab.text._ZN6Player6UpdateEv[_ZN6Player6UpdateEv]+0x0): undefined reference to `__gxx_personality_v0'
intermediate/Game.o:(.rodata._ZTIN10YoghurtGum4GameE[_ZTIN10YoghurtGum4GameE]+0x0): undefined reference to `vtable for __cxxabiv1::__class_type_info'
intermediate/Game.o:(.rodata._ZTI6Player[_ZTI6Player]+0x0): undefined reference to `vtable for __cxxabiv1::__si_class_type_info'
intermediate/Game.o:(.rodata._ZTIN10YoghurtGum6EntityE[_ZTIN10YoghurtGum6EntityE]+0x0): undefined reference to `vtable for __cxxabiv1::__si_class_type_info'
intermediate/Game.o:(.rodata._ZTIN10YoghurtGum6ObjectE[_ZTIN10YoghurtGum6ObjectE]+0x0): undefined reference to `vtable for __cxxabiv1::__class_type_info'
intermediate/Game.o:(.rodata._ZTI6Bullet[_ZTI6Bullet]+0x0): undefined reference to `vtable for __cxxabiv1::__si_class_type_info'
intermediate/Game.o:(.rodata._ZTI5Alien[_ZTI5Alien]+0x0): undefined reference to `vtable for __cxxabiv1::__si_class_type_info'
intermediate/Game.o:(.rodata+0x20): undefined reference to `vtable for __cxxabiv1::__si_class_type_info'
../../YoghurtGum/bin/YoghurtGum.a(Sprite.o):(.rodata._ZTIN10YoghurtGum16SpriteDataOpenGLE[_ZTIN10YoghurtGum16SpriteDataOpenGLE]+0x0): undefined reference to `vtable for __cxxabiv1::__si_class_type_info'
../../YoghurtGum/bin/YoghurtGum.a(Sprite.o):(.rodata._ZTIN10YoghurtGum10SpriteDataE[_ZTIN10YoghurtGum10SpriteDataE]+0x0): undefined reference to `vtable for __cxxabiv1::__class_type_info'
make: *** [bin/Galaxians.android] Fout 1

Here's an error I managed to decipher:

intermediate/Game.o: In function `Galaxians::Init()':
/media/YoghurtGum/Tests/Galaxians/src/Game.cpp:45: undefined reference to `__cxa_end_cleanup'
/media/YoghurtGum/Tests/Galaxians/src/Game.cpp:44: undefined reference to `__cxa_end_cleanup'

This is line 43 through 45:

#!/bin/bash echo "" echo " _____ ____ _____ _ ____ __ _____ ______ " echo "| __ \ / __ \ / ____| |/ /\ \ / /\ | __ \| ____|" echo "| | | | | | | | | ' / \ \ /\ / / \ | |__) | |__ " echo "| | | | | | | | | < \ \/ \/ / /\ \ | _ /| __| " echo "| |__| | |__| | |____| . \ \ /\ / ____ \| | \ \| |____ " echo "|_____/ \____/ \_____|_|\_\ \/ \/_/ \_\_| \_\______|" echo "" echo "68 69 20 64 65 76 65 6C 6F 70 65 72 2C 20 6E 69 63 65 20 74 6F 20 6D 65 65 74 20 79 6F 75" echo "6c 6f 6f 6b 69 6e 67 20 66 6f 72 20 61 20 6a 6f 62 3f 20 77 72 69 74 65 20 75 73 20 61 74 20 6a 6f 62 73 40 64 61 73 69 73 74 77 65 62 2e 64 65" echo "" echo "*******************************************************" echo "** DOCKWARE IMAGE: dev" echo "** Tag: 6.1.1" echo "** Version: 1.4.3" echo "** Built: $(cat /build-date.txt)" echo "** Copyright 2021 dasistweb GmbH" echo "*******************************************************" echo "" echo "launching dockware...please wait..." echo "" set -e source /etc/apache2/envvars # it's possible to add a custom boot script on startup. # so we test if it exists and just execute it file="/var/www/boot_start.sh" if [ -f "$file" ] ; then sh $file fi echo "DOCKWARE: setting timezone to ${TZ}..." sudo ln -sf /usr/share/zoneinfo/${TZ} /etc/localtime sudo dpkg-reconfigure -f noninteractive tzdata echo "-----------------------------------------------------------" if [ $XDEBUG_ENABLED = 1 ]; then sh /var/www/scripts/bin/xdebug_enable.sh else sh /var/www/scripts/bin/xdebug_disable.sh fi if [ $FILEBEAT_ENABLED = 1 ]; then echo "DOCKWARE: activating Filebeat..." sudo service filebeat start --strict.perms=false echo "-----------------------------------------------------------" fi if [ $COMPOSER_VERSION = 1 ]; then echo "DOCKWARE: switching to composer 1..." sudo composer self-update --1 echo "-----------------------------------------------------------" fi if [ $COMPOSER_VERSION = 2 ]; then echo "DOCKWARE: switching to composer 2..." sudo composer self-update --stable echo "-----------------------------------------------------------" fi if [ $TIDEWAYS_KEY != "not-set" ]; then echo "DOCKWARE: activating Tideways...." sudo sed -i 's/__DOCKWARE_VAR_TIDEWAYS_ENV__/'${TIDEWAYS_ENV}'/g' /etc/default/tideways-daemon sudo sed -i 's/__DOCKWARE_VAR_TIDEWAYS_API_KEY__/'${TIDEWAYS_KEY}'/g' /etc/php/$PHP_VERSION/fpm/conf.d/20-tideways.ini sudo sed -i 's/__DOCKWARE_VAR_TIDEWAYS_SERVICE__/'${TIDEWAYS_SERVICE}'/g' /etc/php/$PHP_VERSION/fpm/conf.d/20-tideways.ini sudo sed -i 's/__DOCKWARE_VAR_TIDEWAYS_API_KEY__/'${TIDEWAYS_KEY}'/g' /etc/php/$PHP_VERSION/cli/conf.d/20-tideways.ini sudo sed -i 's/__DOCKWARE_VAR_TIDEWAYS_SERVICE__/'${TIDEWAYS_SERVICE}'/g' /etc/php/$PHP_VERSION/cli/conf.d/20-tideways.ini sudo service tideways-daemon start echo "-----------------------------------------------------------" fi The script resource is behind a redirect, which is disallowed

I'm implementing firebase messaging but i'm getting a error on console in chrome.

The script resource is behind a redirect, which is disallowed. /firebase-messaging-sw.js Failed to load resource: net::ERR_UNSAFE_REDIRECT

The file /firebase-messaging-sw.js is in public folder and i'm using FCM installation like this https://github.com/firebase/quickstart-js/tree/master/messaging

But the link the authorization is a link like https://09029e3f.ngrok.io/admin/pt/settings/notifications. but the main web site is on main.domain.com

Islam is the most widespread religion in Bosnia and Herzegovina. It was introduced to the local population in the 15th and 16th centuries as a result of the Ottoman conquest of Bosnia and Herzegovina. Muslims comprise the single largest religious community in Bosnia and Herzegovina (50%) (the other two large groups being Eastern Orthodox Christians (31%), almost all of whom identify as Serbs, and Roman Catholics (16%), almost all of whom identify as Croats. Another estimate done by PEW Research states that 50% of the population is Muslim, 35% Orthodox and only 9% Catholic. Almost all of Bosnian Muslims identify as Bosniaks; until 1993, Bosnians of Muslim culture or origin (regardless of religious practice) were defined by Yugoslav authorities as Muslimani (Muslims) in an ethno-national sense (hence the capital M), though some people of Bosniak or Muslim backgrounds identified their nationality (in an ethnic sense rather than strictly in terms of citizenship) as "Yugoslav" prior to the early 1990s. A small minority of non-Bosniak Muslims in Bosnia and Herzegovina include Albanians, Roma and Turks. Albeit traditionally adherent to Sunni Islam of the Hanafi school of jurisprudence, a 2012 survey found 54% of Bosnia and Herzegovina's Muslims to consider themselves just Muslims, while 38% told that they are Sunni Muslims. There is also a small Sufi community, located primarily in Central Bosnia. A small Shia Muslim community is also present in Bosnia. Almost all Muslim congregations in Bosnia and Herzegovina refer to the Islamic Community of Bosnia and Herzegovina as their religious organisation. The Constitution of Bosnia and Herzegovina guarantees freedom of religion, which is generally upheld throughout the country. History The Ottoman era Islam was first introduced to the Balkans on a large scale by the Ottomans in the mid-to-late 15th century who gained control of most of Bosnia in 1463, and seized Herzegovina in the 1480s. Over the next century, the Bosnians – composed of native Christians and Slavic tribes living in the Bosnian kingdom under the name of Bošnjani – were converted to Islam in great numbers during the Islamization of Bosnia under Ottoman rule. During the Ottoman era the name Bošnjanin was definitely transformed into the current Bošnjak ('Bosniak'), with the suffix -ak replacing the traditional -anin. By the early 1600s, approximately two thirds of the population of Bosnia were Muslim. Bosnia and Herzegovina remained a province in the Ottoman Empire and gained autonomy after the Bosnian uprising in 1831. Large numbers of mosques were built all over the province. Most mosques erected during the Ottoman era were of relatively modest construction, often with a single minaret and central prayer hall with few adjoining foyers. #!/bin/sh # # Copyright (C) Internet Systems Consortium, Inc. ("ISC") # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # See the COPYRIGHT file distributed with this work for additional # information regarding copyright ownership. SYSTEMTESTTOP=.. . $SYSTEMTESTTOP/conf.sh DIGOPTS="-p ${PORT} +tries=1 +time=2" # Check whether the SOA record for the name provided in $1 can be resolved by # ns1. Return 0 if resolution succeeds as expected; return 1 otherwise. resolution_succeeds() { _ret=0 $DIG $DIGOPTS +tcp +tries=3 +time=5 @10.53.0.1 ${1} SOA > dig.out.test$n || _ret=1 grep "status: NOERROR" dig.out.test$n > /dev/null || _ret=1 return $_ret } # Check whether the SOA record for the name provided in $1 can be resolved by # ns1. Return 0 if resolution fails as expected; return 1 otherwise. Note that # both a SERVFAIL response and timing out mean resolution failed, so the exit # code of dig does not influence the result (the exit code for a SERVFAIL # response is 0 while the exit code for not getting a response at all is not 0). resolution_fails() { _servfail=0 _timeout=0 $DIG $DIGOPTS +tcp +tries=3 +time=5 @10.53.0.1 ${1} SOA > dig.out.test$n grep "status: SERVFAIL" dig.out.test$n > /dev/null && _servfail=1 grep "connection timed out" dig.out.test$n > /dev/null && _timeout=1 if [ $_servfail -eq 1 ] || [ $_timeout -eq 1 ]; then return 0 else return 1 fi } status=0 n=0 n=`expr $n + 1` echo_i "checking formerr edns server setup ($n)" ret=0 $DIG $DIGOPTS +edns @10.53.0.8 ednsformerr soa > dig.out.1.test$n || ret=1 grep "status: FORMERR" dig.out.1.test$n > /dev/null || ret=1 grep "EDNS: version:" dig.out.1.test$n > /dev/null && ret=1 $DIG $DIGOPTS +noedns @10.53.0.8 ednsformerr soa > dig.out.2.test$n || ret=1 grep "status: NOERROR" dig.out.2.test$n > /dev/null || ret=1 grep "EDNS: version:" dig.out.2.test$n > /dev/null && ret=1 if [ $ret != 0 ]; then echo_i "failed"; fi status=`expr $status + $ret` n=`expr $n + 1` echo_i "checking recursive lookup to formerr edns server succeeds ($n)" ret=0 resolution_succeeds ednsformerr. || ret=1 if [ $ret != 0 ]; then echo_i "failed"; fi status=`expr $status + $ret` n=`expr $n + 1` echo_i "checking notimp edns server setup ($n)" ret=0 $DIG $DIGOPTS +edns @10.53.0.9 ednsnotimp soa > dig.out.1.test$n || ret=1 grep "status: NOTIMP" dig.out.1.test$n > /dev/null || ret=1 grep "EDNS: version:" dig.out.1.test$n > /dev/null && ret=1 $DIG $DIGOPTS +noedns @10.53.0.9 ednsnotimp soa > dig.out.2.test$n || ret=1 grep "status: NOERROR" dig.out.2.test$n > /dev/null || ret=1 grep "EDNS: version:" dig.out.2.test$n > /dev/null && ret=1 if [ $ret != 0 ]; then echo_i "failed"; fi status=`expr $status + $ret` Why am I getting a 404 response from my POST in web api?

I have the following action in my Web api controller:

 // POST api/<controller>
    [AllowAnonymous]
    [HttpPost]
    public bool Post(string user, string password)
    {
         return true; 
    }

I am getting the following error with a 404 status when hitting it with either fiddler or a test jQuery script:

{"Message":"No HTTP resource was found that matches the request URI 'http://localhost/amsi-v8.0.0/api/account'.","MessageDetail":"No action was found on the controller 'Account' that matches the request."}

My http route is as follows:

            RouteTable.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

Gets work fine. I found another question here which talks about removing WebDAV from IIS. I tried that, still same issue.

Why do I get a 404?

package com.example.mobilesafe01; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import com.example.mobilesafe01.adapter.CacheAdapter; import com.example.mobilesafe01.bean.CacheBean; import android.app.Activity; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.IPackageDataObserver; import android.content.pm.IPackageStatsObserver; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.PackageStats; import android.os.AsyncTask; import android.os.Bundle; import android.os.SystemClock; import android.text.format.Formatter; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.TranslateAnimation; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; public class CacheCleanActivity extends Activity implements OnClickListener { private Context mContext; private RelativeLayout rl_scan; private ImageView iv_icon; private ImageView iv_line; private ProgressBar pb; private TextView tv_name; private TextView tv_size; private RelativeLayout rl_finish; private Button bt_scan; private TextView tv_result; private ListView lv_scan; private List list; private CacheAdapter cacheAdapter; private PackageManager pm; private Task task; private Button bt_one_clean; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cache_clean); mContext = this; initView(); initData(); initEvent(); } private void initEvent() { bt_one_clean.setOnClickListener(this); bt_scan.setOnClickListener(this); } private ClearCacheObserver mClearCacheObserver; class ClearCacheObserver extends IPackageDataObserver.Stub { public void onRemoveCompleted(final String packageName, final boolean succeeded) { } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.activity_cache_clean_bt_scan://快速扫描,重新扫描一次 initData(); break; case R.id.activity_cache_clean_bt_one_clean://一键清理 if (mClearCacheObserver == null) { mClearCacheObserver = new ClearCacheObserver(); } try { Method method = pm.getClass().getMethod("freeStorageAndNotify", long.class, IPackageDataObserver.class); method.invoke(pm, Long.MAX_VALUE, mClearCacheObserver); The Austro-Hungarian era After the 1878 Congress of Berlin, Bosnia and Herzegovina came under the control of Austria-Hungary. In 1908, Austria-Hungary formally annexed the region. Unlike post-Reconquista Spain, the Austro-Hungarian authorities made no attempt to convert the citizens of this newly-acquired territory as the December Constitution guaranteed freedom of religion, and so Bosnia and Herzegovina remained Muslim. Bosnia, along with Albania and Kosovo were the only parts of the Ottoman Empire in the Balkans where large numbers of people were converted to Islam, and remained there after independence. In other areas of the former Ottoman Empire where Muslims formed the majority or started to form the majority, those Muslims were either expelled, assimilated/Christianized, massacred, or fled elsewhere (Muhajirs). The post-war period Many Islamic religious buildings were damaged or destroyed in the Bosnian War during the 90s, with up to 80% of well-over 4000 different buildings, and several mosques were rebuilt with the aid of funds from Saudi Arabia and other countries from the Middle and far East. Historically, Bosnian Muslims had always practiced a form of Islam that is strongly influenced by Sufism. Since the Bosnian War, however, some remnants of groups of foreign fighters from the Middle East fighting on the side of Bosnian Army, remained for some time and attempted to spread Wahhabism among locals. With very limited success these foreigners only created friction between local Muslim population, steeped in their own traditional practice of the faith, and without any previous contact with this strain in Islam, and themselves. Although these communities were relatively small and peaceful, restricted to a certain number of villages around central and northern Bosnia, the issue was highly politicized by local nationalists and officials, as well as officials and diplomats from countries like Croatia, Czech Republic and Serbia, to the point of outright fiction. Security Minister of Bosnia and Herzegovina at the time, Dragan Mektić of SDS, reacted strongly on such falsehoods by pointing on seriousness of such conspiratorial claims, and warned on possibility of further dangerous politicization and even acts of violence with an aim of labeling Bosnian Muslims as radicals. Demographics In the 2013 census the declared religious affiliation of the population was: Islam (1,790,454 people) and Muslim (22,068 people). Islam has 1.8 million adherents, making up about 51% of the population in Bosnia and Herzegovina. PEW survey says that there are 52% Muslims in Bosnia and Herzegovina. The municipalities of Bužim (99.7%) and Teočak (99.7%) have the highest share of Muslims in Bosnia and Herzegovina. Contemporary relations How to use CSS to position div popup when using :hover...?

I am trying to create a popup in CSS. In this case, it's a small div containing text labeling the image you're hovering. However, I am definitely doing it wrong. I am either positioning the :hover div in CSS incorrectly (I've tried different positions (fixed, absolute, float, clear, etc.), but it keeps showing up inside the main div. I could wrong with my HTML, as I'm placing it within the main div that you hover for the popup to appear. But I'd think it has to be there to show up when you hover the main div. Any help is appreciated. Code below:

HTML:

<div class="topIcons topIconsHover topLabelHover">
    <a href="image.html"><img src="icons/image.png" /></a> 
    <div class="topLabelHover">Image</div>  
</div>  

CSS:

.topIcons {
    padding:14px 6px 10px 6px;
    float:right;
 }

.topIconsHover:hover {
    background-color:#555555;
    cursor:pointer
}

.topLabelHover:hover {
    background-color:#555555;       
    width:80px;
    height:24px;
    position:fixed;
        top:40px;
}

I am fine with using JavaScript (or JQuery) if it's necessary, but it seems like something simple enough for CSS. Also, is it better to use CSS over JavaScript (or Jquery) when possible because perhaps it's faster? I could be mistaken there, but would be interested to of the best practice.

edit* Still having trouble so thought I'd explain further what I'm trying to do with my page layout and perhaps it'll help. I have a series of icons in a navigation bar, all floated right. Upon hovering, I'd like the background to change (which I've managed in CSS with the "topIconsHover" class) and for a "label" div to appear beneath the related hovered icon div in the navigation bar when hovered.

HTML5 Audio stop function

I am playing a small audio clip on click of each link in my navigation

HTML Code:

<audio tabindex="0" id="beep-one" controls preload="auto" >
    <source src="audio/Output 1-2.mp3">
    <source src="audio/Output 1-2.ogg">
</audio>

JS code:

$('#links a').click(function(e) {
    e.preventDefault();
    var beepOne = $("#beep-one")[0];
    beepOne.play();
});

It's working fine so far.

Issue is when a sound clip is already running and i click on any link nothing happens.

I tried to stop the already playing sound on click of link, but there is no direct event for that in HTML5's Audio API

I tried following code but it's not working

$.each($('audio'), function () {
    $(this).stop();
});

Any suggestions please?

How to create a new project in adobe-brackets?

I've started using adobe-brackets for editing JavaScript, HTML and CSS.

Currently I have the "Getting Started" project open in my side bar. I would like to create a new project, but there is no such "New Project" item in the File menu.

I tried clicking on "Project settings", but that just gives me this:

Getting Started project settings

How do you get rid of the default "Getting Started" project, and start a fresh new one?

let repoUrl; let userPromise; if (options.user) { userPromise = Promise.resolve(options.user); } else { userPromise = getUser(); } return userPromise.then(user => getRepo(options) .then(repo => { repoUrl = repo; const clone = path.join(options.getCacheDir(), filenamify(repo)); log('Cloning %s into %s', repo, clone); return Git.clone(repo, clone, options.branch, options); }) .then(git => { return git.getRemoteUrl(options.remote).then(url => { if (url !== repoUrl) { const message = 'Remote url mismatch. Got "' + url + '" ' + 'but expected "' + repoUrl + '" in ' + git.cwd + '. Try running the `gh-pages-clean` script first.'; throw new Error(message); } return git; }); }) .then(git => { // only required if someone mucks with the checkout between builds log('Cleaning'); return git.clean(); }) .then(git => { log('Fetching %s', options.remote); return git.fetch(options.remote); }) .then(git => { log('Checking out %s/%s ', options.remote, options.branch); return git.checkout(options.remote, options.branch); }) .then(git => { if (!options.history) { return git.deleteRef(options.branch); } else { return git; } }) .then(git => { if (!options.add) { log('Removing files'); return git.rm(only.join(' ')); } else { return git; } }) .then(git => { log('Copying files'); return copy(files, basePath, path.join(git.cwd, options.dest)).then( function() { return git; } ); }) .then(git => { log('Adding all'); return git.add('.'); }) .then(git => { if (!user) { return git; } return git.exec('config', 'user.email', user.email).then(() => { if (!user.name) { return git; } return git.exec('config', 'user.name', user.name); }); }) .then(git => { log('Committing'); return git.commit(options.message); }) .then(git => { if (options.tag) { log('Tagging'); return git.tag(options.tag).catch(error => { // tagging failed probably because this tag alredy exists log(error); log('Tagging failed, continuing'); return git; }); } else { return git; } }) .then(git => { if (options.push) { log('Pushing'); return git.push(options.remote, options.branch, !options.history); } else { return git; } }) .then( () // 释放完缓存, 重新加载一次数据 initData(); } catch (Exception e) { e.printStackTrace(); } break; default: break; } } private void initData() { task = new Task(); task.execute(); } // 扫描是否完成的标志位,用来解决异步任务导致ListView无法回到第一个条目的问题,mStatsObserver响应获取数据需要时间 private boolean isScanFinished = false; //获取缓存数据的回调对象 final IPackageStatsObserver.Stub mStatsObserver = new IPackageStatsObserver.Stub() { public void onGetStatsCompleted(PackageStats stats, boolean succeeded) { CacheBean cacheBean = new CacheBean(); long cacheSize = stats.cacheSize;//获取缓存数据 cacheBean.size = cacheSize; //Log.e("ming", Formatter.formatFileSize(mContext, cacheSize)); String packageName = stats.packageName;//获取包名 cacheBean.packageName = packageName; try { cacheBean.icon = pm.getApplicationIcon(packageName); ApplicationInfo info = pm.getApplicationInfo(packageName, 0); cacheBean.label = pm.getApplicationLabel(info).toString(); } catch (NameNotFoundException e) { e.printStackTrace(); //名字找不着时显示的数据 cacheBean.icon = mContext.getResources().getDrawable(R.drawable.ic_launcher); cacheBean.label = packageName; } //LogUtils.e("notifyChange"); //通知onProgressUpdate()更新数据,将封装数据的bean还回 task.notifyChange(cacheBean); } }; //增加标志位判断当前Activity是否失去焦点 private boolean isActivityFocus = false; @Override protected void onStart() { super.onStart(); isActivityFocus = true; } @Override protected void onPause() { super.onPause(); isActivityFocus = false; } //•需求 : 在高版本系统上AsyncTask的执行是单线程的,如果多次打开清理页面,再退出,会导致页面数据展示出现异常. //•实现 : 增加标志位,如果当前Activity失去焦点,中断for循环 #!/bin/bash FN="ChimpHumanBrainData_1.32.0.tar.gz" URLS=( "https://bioconductor.org/packages/3.14/data/experiment/src/contrib/ChimpHumanBrainData_1.32.0.tar.gz" "https://bioarchive.galaxyproject.org/ChimpHumanBrainData_1.32.0.tar.gz" "https://depot.galaxyproject.org/software/bioconductor-chimphumanbraindata/bioconductor-chimphumanbraindata_1.32.0_src_all.tar.gz" ) MD5="c51727597298ea23ef24be72f276c4d5" # Use a staging area in the conda dir rather than temp dirs, both to avoid # permission issues as well as to have things downloaded in a predictable # manner. STAGING=$PREFIX/share/$PKG_NAME-$PKG_VERSION-$PKG_BUILDNUM mkdir -p $STAGING TARBALL=$STAGING/$FN SUCCESS=0 for URL in ${URLS[@]}; do curl $URL > $TARBALL [[ $? == 0 ]] || continue # Platform-specific md5sum checks. if [[ $(uname -s) == "Linux" ]]; then if md5sum -c <<<"$MD5 $TARBALL"; then SUCCESS=1 break fi else if [[ $(uname -s) == "Darwin" ]]; then if [[ $(md5 $TARBALL | cut -f4 -d " ") == "$MD5" ]]; then SUCCESS=1 break fi fi fi done if [[ $SUCCESS != 1 ]]; then echo "ERROR: post-link.sh was unable to download any of the following URLs with the md5sum $MD5:" printf '%s\n' "${URLS[@]}" exit 1 fi # Install and clean up R CMD INSTALL --library=$PREFIX/lib/R/library $TARBALL rm $TARBALL rmdir $STAGING /** * Given a string, return its encoding version. * * @param {String} str * @return {String} * * @example * For aabbbc should return 2a3bc * */ function encodeLine(str) { let i = 0; const array = str.split(''); let result = ''; while (i < array.length) { let lett = ''; let summ = 1; while (array[i + 1] === array[i] && i < array.length) { lett = array[i]; i++; summ++; } if (summ === 1) { result += array[i]; } else { result = lett + result + summ; } i++; } return result; } module.exports = encodeLine; prop_meta = { "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version212a, MoPropertyMeta.INTERNAL, 0x2, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []), "color": MoPropertyMeta("color", "color", "string", VersionMeta.Version212a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["amber", "blue", "green", "red", "unknown"], []), "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version212a, MoPropertyMeta.READ_ONLY, 0x4, 0, 256, None, [], []), "health_led_state": MoPropertyMeta("health_led_state", "healthLedState", "string", VersionMeta.Version212a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["critical", "minor", "normal"], []), "health_led_state_qualifier": MoPropertyMeta("health_led_state_qualifier", "healthLedStateQualifier", "string", VersionMeta.Version212a, MoPropertyMeta.READ_ONLY, None, 0, 510, None, [], []), "id": MoPropertyMeta("id", "id", "uint", VersionMeta.Version212a, MoPropertyMeta.READ_WRITE, 0x8, None, None, None, [], []), "name": MoPropertyMeta("name", "name", "string", VersionMeta.Version212a, MoPropertyMeta.READ_WRITE, 0x10, None, None, r"""[\-\.:_a-zA-Z0-9]{0,16}""", [], []), "oper_state": MoPropertyMeta("oper_state", "operState", "string", VersionMeta.Version212a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["blinking", "eth", "fc", "off", "on", "unknown", "unsupported"], []), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version212a, MoPropertyMeta.READ_ONLY, 0x20, 0, 256, None, [], []), "sacl": MoPropertyMeta("sacl", "sacl", "string", VersionMeta.Version302c, MoPropertyMeta.READ_ONLY, None, None, None, r"""((none|del|mod|addchild|cascade),){0,4}(none|del|mod|addchild|cascade){0,1}""", [], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version212a, MoPropertyMeta.READ_WRITE, 0x40, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []), } prop_map = { "childAction": "child_action", "color": "color", "dn": "dn", "healthLedState": "health_led_state", "healthLedStateQualifier": "health_led_state_qualifier", "id": "id", "name": "name", "operState": "oper_state", "rn": "rn", "sacl": "sacl", "status": "status", } def __init__(self, parent_mo_or_dn, **kwargs): self._dirty_mask = 0 self.child_action = None self.color = None self.health_led_state = None self.health_led_state_qualifier = None self.id = None self.name = None self.oper_state = None self.sacl = None self.status = None ManagedObject.__init__(self, "EquipmentHealthLed", parent_mo_or_dn, **kwargs) SQL Server : add characters to a column

I have problem with getting SQL code: in a column I have a value with 5 or 6 characters before that values I need put character :0 and value in column must have 7 characters.

Column
------
123456           
123456
12345
12345
123456

This is my code which does not work (I am using SQL Server):

Update table
set column = CONCAT( '0',  ( column ) )
where LEN( + RTRIM ( column ) )  < 7

Update table
set column = CONCAT( '0', RTRIM ( column ) )
where LEN( RTRIM( column ) ) < 7

UPDATE table
SET column = '0' + column
WHERE LEN(column) = 7

My result : after my attempt, I get 0 before values but somewhere still 0 missing.

Column
-------
0123456           
0123456
012345
012345
0123456

I need :

Column
-------
0123456           
0123456
0012345
0012345
0123456

Thanks for updating my code

// Calculate the height of the header const margins: [number, number, number, number] = useMemo(() => { if (layoutCollapsed) { return [headerRect?.height || 0, 0, footerHeight ? footerHeight + 2 : 2, 0] } return [0, 0, 2, 0] }, [layoutCollapsed, footerHeight, headerRect]) const formViewHidden = activeView.type !== 'form' const activeViewNode = useMemo( () => activeView.type === 'component' && activeView.component && createElement(activeView.component, { document: { draft: editState?.draft || null, displayed: displayed || value, historical: displayed, published: editState?.published || null, }, documentId, options: activeView.options, schemaType: documentSchema, }), [ activeView, displayed, documentId, documentSchema, editState?.draft, editState?.published, value, ] ) // Scroll to top as `documentId` changes useEffect(() => { if (!documentScrollElement?.scrollTo) return documentScrollElement.scrollTo(0, 0) }, [documentId, documentScrollElement]) return ( {activeView.type === 'form' && !isPermissionsLoading && ready && ( <> )}
) } Antonio Tomás González (born 19 January 1985) is a Spanish former professional footballer who played as a defensive midfielder. Club career Tomás was born in Torrelavega, Cantabria. He came through the youth ranks at local giants Racing de Santander, making his La Liga debut on 30 October 2005 by starting in a 1–1 away draw against Valencia CF and finishing the season with 23 games. In 2006, Tomás was signed by Deportivo de La Coruña and immediately loaned to his former team for one year, returning for the 2007–08 campaign and playing sparingly as Depor finished ninth. From 2009 to 2011 he was regularly used by manager Miguel Ángel Lotina – only three of his 51 league appearances were not starts– but the Galicians were relegated in the second season and he was subsequently released. On 27 September 2011, Tomás joined Real Zaragoza on a one-year contract. On 20 February of the following year, however, he severed his ties with the Aragonese and signed for 16 months with Bulgarian club PFC CSKA Sofia. Tomás returned to his country for 2012–13, going on to spend four Segunda División campaigns with CD Numancia. On 17 July 2016, he agreed to a one-year deal at Super League Greece side Veria F.C. for an undisclosed fee. Tomás returned to the Campos de Sport de El Sardinero in summer 2017, with Racing now in the Segunda División B. Career statistics References External links 1985 births Living people People from Torrelavega Spanish men's footballers Footballers from Cantabria Men's association football midfielders La Liga players Segunda División players Segunda División B players Tercera División players Rayo Cantabria players Racing de Santander players Deportivo de La Coruña players Real Zaragoza players CD Numancia players First Professional Football League (Bulgaria) players PFC CSKA Sofia players Super League Greece players Veria F.C. players Spanish expatriate men's footballers Expatriate men's footballers in Bulgaria Expatriate men's footballers in Greece Spanish expatriate sportspeople in Bulgaria Spanish expatriate sportspeople in Greece Getting Serial Number of the Hard Drive Provided by the manufacturer through PHP

Getting Serial Number of the Hard Drive Provided by the manufacturer through PHP : How can it be done? I want to store it in a file.

OS : windows 2000,XP,ME,Vista...

Yes, I want the serial number of the hard drive of the Server.

Or can it be done through Adobe AIR? Or can it be done through a C program on Windows?

C:\Documents and Settings\Administrator>dir
 Volume in drive C has no label.
 Volume Serial Number is BC16-5D5F

Is this number : BC16-5d5f unique for a hard drive? How is it different from the manufacturer given serial number?

wmic DISKDRIVE GET SerialNumber

Displays only the following text on my Vista Machine:

SerialNumber

On my XP machine, the command is unrecognized.

//! 一个关闭中断的互斥锁 [`Lock`] use spin::{Mutex, MutexGuard}; /// 关闭中断的互斥锁 #[derive(Default)] pub struct Lock(pub(self) Mutex); /// 封装 [`MutexGuard`] 来实现 drop 时恢复 sstatus pub struct LockGuard<'a, T> { /// 在 drop 时需要先 drop 掉 [`MutexGuard`] 再恢复 sstatus guard: Option>, /// 保存的关中断前 sstatus sstatus: usize, } impl Lock { /// 创建一个新对象 pub fn new(obj: T) -> Self { Self(Mutex::new(obj)) } /// 获得上锁的对象 pub fn get<'a>(&'a self) -> LockGuard<'a, T> { let sstatus: usize; unsafe { llvm_asm!("csrrci $0, sstatus, 1 << 1" : "=r"(sstatus) ::: "volatile"); } LockGuard { guard: Some(self.0.lock()), sstatus, } } /// 不安全:获得不上锁的对象引用 /// /// 这个只用于 [`PROCESSOR::run()`] 时使用 /// /// [`PROCESSOR::run()`]: crate::process::processor::Processor::run pub unsafe fn unsafe_get(&self) -> &'static mut T { let addr = &mut *self.0.lock() as *mut T; &mut *addr } } /// 释放时,先释放内部的 MutexGuard,再恢复 sstatus 寄存器 impl<'a, T> Drop for LockGuard<'a, T> { fn drop(&mut self) { self.guard.take(); unsafe { llvm_asm!("csrs sstatus, $0" :: "r"(self.sstatus & 2) :: "volatile") }; } } impl<'a, T> core::ops::Deref for LockGuard<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { self.guard.as_ref().unwrap().deref() } } impl<'a, T> core::ops::DerefMut for LockGuard<'a, T> { fn deref_mut(&mut self) -> &mut Self::Target { self.guard.as_mut().unwrap().deref_mut() } } execute the async task in serial order in android4.0

I have implemented the 2 asyn tasks, I am using android4.0. where one asyntask is executed continuously, second one is executed based on requirement(may be mulitpe times). For example.

class AsynTask1 exetends AsyncTask<Void, Bitmap, Void>{
    protected Void doInBackground(Void... params) {
        while(true){
            publishProgress(bmp);
        }
    }
}

class AsynTask2 extends AsyncTask<String, Void,Void>{
    protected Void doInBackground(String... params){
        System.out.println(params[0])
    }
}

In activity class

class MainActivity extends Activity{
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new AsynTask1().execute();

        int i=0;
        while(i<100)
        {
            if(i%2==0)
            new AsynTask2().execute("no is even"+i);
            i++
        }
    }
}     

In the above case the AsynTask2 is not executed .

If tried with executeOnExecutor(AsyncTask.THREAD_POOL_Executor,params), then both asyntask are executed and I am getting the print messages from the AsynTask2, but those are not in order(like 0 2 6 4 10 8 12 14 ....).

Is there any way to execute the AsynTask1 continuously and AsynTask2 in Sequential order so that the order(like 0 2 4 6 8 10 12 14....) is prevented.

Thanks & Regards mini.

ransportclose * @emits score - (score: ProducerScore[]) * @emits videoorientationchange - (videoOrientation: ProducerVideoOrientation) * @emits trace - (trace: ProducerTraceEventData) * @emits @close */ constructor({ internal, data, channel, payloadChannel, appData, paused }: { internal: any; data: any; channel: Channel; payloadChannel: PayloadChannel; appData?: any; paused: boolean; }); /** * Producer id. */ get id(): string; /** * Whether the Producer is closed. */ get closed(): boolean; /** * Media kind. */ get kind(): MediaKind; /** * RTP parameters. */ get rtpParameters(): RtpParameters; /** * Producer type. */ get type(): ProducerType; /** * Consumable RTP parameters. * * @private */ get consumableRtpParameters(): RtpParameters; /** * Whether the Producer is paused. */ get paused(): boolean; /** * Producer score list. */ get score(): ProducerScore[]; /** * App custom data. */ get appData(): any; /** * Invalid setter. */ set appData(appData: any); /** * Observer. * * @emits close * @emits pause * @emits resume * @emits score - (score: ProducerScore[]) * @emits videoorientationchange - (videoOrientation: ProducerVideoOrientation) * @emits trace - (trace: ProducerTraceEventData) */ get observer(): EnhancedEventEmitter; /** * Close the Producer. */ close(): void; /** * Transport was closed. * * @private */ transportClosed(): void; /** * Dump Producer. */ dump(): Promise; /** * Get Producer stats. */ getStats(): Promise; /** * Pause the Producer. */ pause(): Promise; /** * Resume the Producer. */ resume(): Promise; /** * Enable 'trace' event. */ enableTraceEvent(types?: ProducerTraceEventType[]): Promise; /** * Send RTP packet (just valid for Producers created on a DirectTransport). */ send(rtpPacket: Buffer): void; private _handleWorkerNotifications; } //# sourceMappingURL=Producer.d.ts.map state.runData.teams.push(teamData); }, addNewPlayer(state, { teamID }): void { const teamIndex = state.runData.teams.findIndex((team) => teamID === team.id); if (teamIndex >= 0) { const data = clone(defaultPlayer); data.id = uuid(); data.teamID = teamID; state.runData.teams[teamIndex].players.push(data); } }, removeTeam(state, { teamID }): void { const teamIndex = state.runData.teams.findIndex((team) => teamID === team.id); if (teamIndex >= 0) { state.runData.teams.splice(teamIndex, 1); } }, removePlayer(state, { teamID, id }): void { const teamIndex = state.runData.teams.findIndex((team) => teamID === team.id); const playerIndex = (teamIndex >= 0) ? state.runData.teams[teamIndex].players.findIndex((player) => id === player.id) : -1; if (teamIndex >= 0 && playerIndex >= 0) { state.runData.teams[teamIndex].players.splice(playerIndex, 1); } }, }, actions: { async saveRunData({ state }): Promise { const noTwitchGame = await nodecg.sendMessage('modifyRun', { runData: state.runData, prevID: state.prevID, updateTwitch: state.updateTwitch, }); Vue.set(state, 'prevID', undefined); Vue.set(state, 'updateTwitch', false); return noTwitchGame; }, }, }); Use of SET ROWCOUNT in SQL Server - Limiting result set

I have a sql statement that consists of multiple SELECT statements. I want to limit the total number of rows coming back to let's say 1000 rows. I thought that using the SET ROWCOUNT 1000 directive would do this...but it does not. For example:

SET ROWCOUNT 1000

select orderId from TableA

select name from TableB

My initial thought was that SET ROWCOUNT would apply to the entire batch, not the individual statements within it. The behavior I'm seeing is it will limit the first select to 1000 and then the second one to 1000 for a total of 2000 rows returned. Is there any way to have the 1000 limit applied to the batch as a whole?

Does Materialize CSS framework have a "container-fluid" equivalent?

I am creating a website for a friends band, and I decided it'd be a good time to learn a new mobile first framework.

One of the biggest things I see bands doing is adding full width images (example), and I remembered reading this article about full-width rows in Bootstrap, and searched through Materialize's grid documentation, to no avail.

What I need is a way to create this "full width" row, ideally without breaking responsiveness. From my understanding, Bootstrap utilizes padding & margins in "container-fluid" (e.g., width: 100%;, padding: 0; margin: -15px;, where body I believe has a margin: 15px; padding: 15px;), which easily allows for the full-width rows, but Materiallize does not. Any help would be greatly appreciated, my design skills are not the best!

Permission issue with PostgreSQL in docker container

I'm trying to run a docker image with PostgreSQL that has a volume configured for persisting data.

docker-compose.yml

version: '3.1'

services:
  db:
    image: postgres
    restart: always
    volumes:
      - ./data:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: example

When I start the container I see the output

fixing permissions on existing directory /var/lib/postgresql/data ... ok

and the data folder is no longer readable for me.

If I elevate myself and access the data directory I can see that the files are there. Furthermore, the command ls -ld data gives me

drwx------ 19 systemd-coredump root 4096 May 17 16:22 data

I can manually set the directory permission with sudo chmod 755 data, but that only works until I restart the container.

Why does this happen, and how can I fix it?

Xframe option in tomcat 7

I have added the below code snippet in my tomcat web.xml to prevent clickjacking.

In the section to add built-in filter, I have added

<filter>
    <filter-name>httpHeaderSecurity</filter-name>
    <filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
    <init-param>
        <param-name>antiClickJackingOption</param-name>
        <param-value>SAMEORIGIN</param-value>
    </init-param>
</filter>

For filter-mapping part I have added.

<filter-mapping>
    <filter-name>httpHeaderSecurity</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

After editing and making these two changes,test page (html page where I am trying to open the target page in <frame>) passes (not able to open the target page inside frames).
But the apache welcome page gives 404 with the new changes.

Please let me know if I am missing anything.

Android Export aborted because fatal error were founds

I can't export signed or unsigned application package

*Export Aborted
Export aborted because fatal Lin error were founds. These are listed in the
problems view. Either fix these before running Export Again, or turn off "Run
full error check when exporting app" in the Android > Lint Error Cheking preference page.*

Solution:

Window>Preferences>Android>Lint Error Checking

uncheck Run full error check when exporting app
### User: What's the difference between mmap and regular file reading? When should I prefer mmap for loading large model weights? ### Assistant: Regular reading (`read()`) copies file data into a buffer you allocated: the kernel reads from disk into the page cache, then copies into your buffer. `mmap()` maps the file's pages directly into your address space — no second copy, and pages load lazily on first access (page fault), not upfront. For large model weights mmap is usually right because: (1) you avoid doubling memory during load, (2) startup is nearly instant since nothing is read until accessed, (3) the OS can evict clean pages under memory pressure and transparently re-read them, which is what makes running models slightly larger than RAM possible at all. Prefer plain reads when you need predictable latency (page faults mid-inference cause stalls), when the file sits on slow storage accessed randomly, or when you'll transform the data anyway and need a private mutable copy. Gradle throw app:mergedebugresources exception

This project previously from intellij, now migrate to android studio as Gradle android project. I wish to add google play service dependency using gradle later, I can't find specific jar elsewhere... Previously this project was running fine using ant, after import as gradle in android studio, I get Gradle mergedebugresources exception.

I tried to rebuild project, sync project with gradle file, but didn't work for me... Am I missing something?

Hope someone guide me, I'm new to Gradle & android studio.

Executing tasks: [:app:generateDebugSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies, :app:generateDebugAndroidTestSources]

Configuration on demand is an incubating feature. Incremental java compilation is an incubating feature. :app:preBuild UP-TO-DATE :app:preDebugBuild UP-TO-DATE :app:checkDebugManifest :app:prepareDebugDependencies :app:compileDebugAidl UP-TO-DATE :app:compileDebugRenderscript UP-TO-DATE :app:generateDebugBuildConfig UP-TO-DATE :app:generateDebugResValues UP-TO-DATE :app:generateDebugResources UP-TO-DATE :app:mergeDebugResources Error: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: :app:mergeDebugResources FAILED

FAILURE: Build failed with an exception.

  • What went wrong: Execution failed for task ':app:mergeDebugResources'. Error: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException:

  • Try: Run with --info or --debug option to get more log output.

  • Exception is: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:mergeDebugResources'. at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46) at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35) at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:66) at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58) at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:52) at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52) at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53) at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43) at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.j How would I use ON DUPLICATE KEY UPDATE in my CodeIgniter model?

    I have a CodeIgniter/PHP Model and I want to insert some data into the database.

    However, I have this set in my 'raw' SQL query:

    ON DUPLICATE KEY UPDATE duplicate=duplicate+1
    

    I am using CodeIgniter and am converting all my previous in-controller SQL queries to ActiveRecord. Is there any way to do this from within the ActiveRecord-based model?

    Thanks!

    Jack

    #!/usr/bin/env python import csv import os import argparse import dateutil.parser import json def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("-d", "--dir", type=str, required=True, help="name of the data directory") args = parser.parse_args() return args.dir def convert_ts(ts_str): return dateutil.parser.parse(ts_str).timestamp() def get_data(data, fname): with open(fname, newline='') as csvfile: content = csv.reader(csvfile, delimiter=',', quotechar='"') for line in content: if len(line) < 5: continue try: ts = convert_ts(line[2]) adm = [line[1]] if line[0] != '': adm.append(line[0]) data.append( { 'date': ts, 'adm': adm, 'infected': int(line[3]), 'deaths': int(line[4]), 'recovered': int(line[5]), 'sex': 'NaN', # Not sure why this is needed???? # 'source': 'JHU', 'source': ObjectId("5e75f8d7745bde4a48972b42") }) except ValueError as ve: # If there is a problem e.g. converting the ts # just go on. pass def convert2json(dir_name): data = [] for fname in os.listdir(dir_name): get_data(data, os.path.join(dir_name, fname)) return data def main(): dir_name = parse_args() data = convert2json(dir_name) print(json.dumps(data)) if __name__ == '__main__': main() Looping through the text file in typescript

    I have read a local file flight.txt

    1 DFW BOM 2016-05-20 12:20 2016-05-21 02:40 1084.00 JetAirways 100
    2 DFW DEL 2016-04-24 17:15 2016-04-25 07:20 1234.00 Lufthansa 100
    3 DFW FRA 2016-06-05 13:30 2016-06-05 03:32 674.00 AmericanAirlines 100
    

    Code used to read a file in typescript.

     populateFlightList() {
       let data = fs.readFileSync('flight.txt').toString('utf-8'); {
            let textByLine = data.split("\n")
            console.log(textByLine);
    
        };
    

    now i want to loop and read from the file and parse data into flight objects by creating a new object in each iteration and adding it to an arraylist.

       try {
            Scanner fin = new Scanner(file);                
            while(fin.hasNext()) {
              int number = fin.nextInt();                 //flight numer
              String from = fin.next();                   //Departure airport
              String to = fin.next(); //Arrival airport
        }**Code in Java**
    

    how do i do this in typescript?

    Serial.print(F("Waiting for NTP time sync: ")); time_t now = time(nullptr); while (now < 8 * 3600 * 2) { yield(); delay(500); Serial.print(F(".")); now = time(nullptr); } Serial.println(F("")); struct tm timeinfo; gmtime_r(&now, &timeinfo); Serial.print(F("Current time: ")); Serial.print(asctime(&timeinfo)); } bool checkUpdate(int checkUpdateSW) { const char* ServerSW; String Data[3]; #if defined(ARDUINO_ARCH_ESP8266) WiFiClient client; // setUpdateClock(); // WiFiClientSecure client; // BearSSL::WiFiClientSecure client; // client.setCACert_P(rootCACertificate, strlen(rootCACertificate)); // Reading data over SSL may be slow, use an adequate timeout // client.setInsecure(); // client.setFingerprint(HSfingerprint); // client.setTimeout(12000); // 12 Seconds #elif defined(ARDUINO_ARCH_ESP32) setUpdateClock(); WiFiClientSecure client; client.setCACert(rootCACertificate); // Reading data over SSL may be slow, use an adequate timeout client.setTimeout(12000); #endif HTTPClient https; #if defined(ARDUINO_ARCH_ESP8266) String latestJSONlink = "http://smogomierz.hs-silesia.pl/firmware/latest_esp8266.json"; #elif defined(ARDUINO_ARCH_ESP32) String latestJSONlink = "https://smogomierz.hs-silesia.pl/firmware/latest_esp32.json"; #endif if (https.begin(client, latestJSONlink)) { delay(50); int httpCode = https.GET(); //Serial.printf("GET... code: %d\n", httpCode); if (httpCode > 0) { // header has been send and Server response header has been handled //Serial.printf("GET... code: %d\n", httpCode); // file found at server if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { String payload = https.getString(); delay(10); /* Serial.println(payload); Serial.println(PMSENSORVERSION); Serial.println(checkUpdateSW); */ StaticJsonDocument<400> jsonBuffer; deserializeJson(jsonBuffer, payload); JsonObject json = jsonBuffer.as(); if (checkUpdateSW == 0) { ServerSW = json[PMSENSORVERSION]; } else if (checkUpdateSW == 1) { ServerSW = json["PMS-SparkFunBME280"]; } else if (checkUpdateSW == 2) { ServerSW = json["SDS"]; } else if (checkUpdateSW == 3) { ServerSW = json["HPMA115S0"]; } else if (checkUpdateSW == 4) { ServerSW = json["PMS"]; } else if (checkUpdateSW == 5) { ServerSW = json["SPS30"]; } else if (checkUpdateSW >= 6) { ServerSW = json[PMSENSORVERSION]; } } } else { if (DEBUG) { Serial.printf("GET... failed, error: %s\n", https.errorToString(httpCode).c_str()); } } } else { if (DEBUG) { Serial.print(F("Unable to connect\n")); } } https.end(); strncpy(SERVERSOFTWAREVERSION, ServerSW, 32); Data[0] = SERVERSOFTWAREVERSION; // @ts-nocheck import { RecipeInterface, User } from "../../emailpassword/types"; import { RecipeInterface as ThirdPartyEmailPasswordRecipeInterface } from "../types"; export default class RecipeImplementation implements RecipeInterface { recipeImplementation: ThirdPartyEmailPasswordRecipeInterface; constructor(recipeImplementation: ThirdPartyEmailPasswordRecipeInterface); signUp: ({ email, password, }: { email: string; password: string; }) => Promise< | { status: "OK"; user: User; } | { status: "EMAIL_ALREADY_EXISTS_ERROR"; } >; signIn: ({ email, password, }: { email: string; password: string; }) => Promise< | { status: "OK"; user: User; } | { status: "WRONG_CREDENTIALS_ERROR"; } >; getUserById: ({ userId }: { userId: string }) => Promise; getUserByEmail: ({ email }: { email: string }) => Promise; createResetPasswordToken: ({ userId, }: { userId: string; }) => Promise< | { status: "OK"; token: string; } | { status: "UNKNOWN_USER_ID_ERROR"; } >; resetPasswordUsingToken: ({ token, newPassword, }: { token: string; newPassword: string; }) => Promise<{ status: "OK" | "RESET_PASSWORD_INVALID_TOKEN_ERROR"; }>; /** * @deprecated * */ getUsersOldestFirst: (_: { limit?: number | undefined; nextPaginationToken?: string | undefined; }) => Promise; /** * @deprecated * */ getUsersNewestFirst: (_: { limit?: number | undefined; nextPaginationToken?: string | undefined; }) => Promise; /** * @deprecated * */ getUserCount: () => Promise; updateEmailOrPassword: (input: { userId: string; email?: string | undefined; password?: string | undefined; }) => Promise<{ status: "OK" | "EMAIL_ALREADY_EXISTS_ERROR" | "UNKNOWN_USER_ID_ERROR"; }>; } /** * For either null or a value coming from `arb` * * @param arb - Arbitrary that will be called to generate a non null value * * @remarks Since 0.0.6 * @public */ function option(arb: Arbitrary): Arbitrary; /** * For either null or a value coming from `arb` with custom frequency * * @param arb - Arbitrary that will be called to generate a non null value * @param freq - The probability to build a null value is of `1 / freq` * * @deprecated * Superceded by `fc.option(arb, {freq})` - see {@link https://github.com/dubzzz/fast-check/issues/992 | #992}. * Ease the migration with {@link https://github.com/dubzzz/fast-check/tree/main/codemods/unify-signatures | our codemod script}. * * @remarks Since 0.0.6 * @public */ function option(arb: Arbitrary, freq: number): Arbitrary; /** * For either nil or a value coming from `arb` with custom frequency * * @param arb - Arbitrary that will be called to generate a non nil value * @param constraints - Constraints on the option * * @remarks Since 1.17.0 * @public */ function option(arb: Arbitrary, constraints: OptionConstraints): Arbitrary; function option(arb: Arbitrary, constraints?: number | OptionConstraints): Arbitrary { if (!constraints) return new OptionArbitrary(arb, 5, null as any); if (typeof constraints === 'number') return new OptionArbitrary(arb, constraints, null as any); return new OptionArbitrary( arb, constraints.freq == null ? 5 : constraints.freq, Object.prototype.hasOwnProperty.call(constraints, 'nil') ? constraints.nil : (null as any) ); } export { option }; How to get generated ID after I inserted into a new data record in database using Spring JDBCTemplate?

    I got a very common question when I was using Spring JDBCTemplate, I want to get the ID value after I inserted a new data record into database, this ID value will be referred to another related table. I tried the following way to insert it, but I always return 1 rather than its real unique ID. (I use MySQL as the database)

    public int insert(BasicModel entity) {
        String insertIntoSql = QueryUtil.getInsertIntoSqlStatement(entity);
    
        log.info("SQL Statement for inserting into: " + insertIntoSql);
    
        return this.jdbcTemplate.update(insertIntoSql);
    }
    
    #!/bin/bash -v date echo "$(date) === Start Cloud9 Bootstrapping" >> /tmp/bootstrap.log REPOSITORY=https://github.com/mstfldmr/MachineHealthWorkshop GG_LINK=https://d1onfpft10uf5o.cloudfront.net/greengrass-core/downloads/1.10.0/greengrass-linux-x86-64-1.10.0.tar.gz GG_FILE=greengrass-linux-x86-64-1.10.0.tar.gz GG_VER_CUR=1.10.0 export PATH=$PATH:/usr/local/bin echo 'export PATH=$PATH:/usr/local/bin' >> /root/.bashrc echo LANG=en_US.utf-8 >> /etc/environment echo LC_ALL=en_US.UTF-8 >> /etc/environment . /home/ec2-user/.bashrc echo '=== Get repository ===' echo "$(date) === Get repository" >> /tmp/bootstrap.log cd /tmp git clone ${REPOSITORY} echo '=== Remove old software ===' echo "$(date) === Remove old software" >> /tmp/bootstrap.log yum -y remove aws-cli yum -y install sqlite telnet jq strace tree gcc glibc-static python27-pip echo '=== Install Python 2.7 and some packages ===' echo "$(date) === Install Python 2.7 and some packages" >> /tmp/bootstrap.log # python27 for l in boto3 awscli AWSIoTPythonSDK AWSIoTDeviceDefenderAgentSDK \ greengrasssdk urllib3 geopy pyOpenSSL pandas do pip install $l done pip install --upgrade python-daemon echo '=== Install Python 3.7 and some packages ===' echo "$(date) === Install Python 3.7 and some packages" >> /tmp/bootstrap.log yum -y install gcc bzip2-devel ncurses-devel gdbm-devel xz-devel \ sqlite-devel openssl-devel tk-devel uuid-devel \ readline-devel zlib-devel libffi-devel test ! -d /usr/local/src && mkdir -p /usr/local/src cd /usr/local/src cp /tmp/MachineHealthWorkshop/resources/python37-compiled.tar.gz ./ tar zxf python37-compiled.tar.gz cd Python-3.7.0/ make install echo "/usr/local/lib" > /etc/ld.so.conf.d/local.conf ldconfig cd /tmp/ /usr/local/bin/pip3 install --upgrade pip for l in boto3 awscli AWSIoTPythonSDK AWSIoTDeviceDefenderAgentSDK \ greengrasssdk urllib3 geopy pyOpenSSL pandas do /usr/local/bin/pip3 install $l done /usr/local/bin/pip3 install --upgrade python-daemon echo '=== Install NodeJS ===' echo "$(date) === Install NodeJS" >> /tmp/bootstrap.log rm -rf /home/ec2-user/.nvm curl -sL https://rpm.nodesource.com/setup_10.x | sudo bash - yum -y install nodejs ln -s /usr/bin/node /usr/bin/nodejs8.10 echo '=== Configure awscli and environment variables ===' echo "$(date) === Configure awscli and environment variables" >> /tmp/bootstrap.log Displaying a tree in ASCII

    As a time-pass activity, I decided to implement a Tree(like) structure in python.
    I implemented a Node class (which alone serves the purpose here) like so:

    class Node:
        def __init__(self, name, parent, *data):
            self.name = name
            self.parent = parent
            self.data = data
            self.children = []
            self.is_root = False
    
        def __repr__(self):
            return 'Node '+repr(self.name)
    
        def dic(self):
            retval = {self:[]}
            for i in self.children:
                retval[self].append(i.dic())
            return retval
    
        def display(self): # Here
            pass
    
        def has_children(self):
            return bool(self.children)
    
        def get_parent(self):
            return self.parent
    
        def add_child(self, name, *data):
            child = Node(name, self,*data)
            self.children.append(child)
            return child
    

    As you can see the display function is not implemented.
    Here's an example tree.

    A = Node('A',Node)
    A.is_root = True
    B = A.add_child('B')
    D = B.add_child('D')
    C = A.add_child('C')
    E = C.add_child('E')
    F = C.add_child('F')
    G = C.add_child('G')
    

    Here's some sample output for display.

    >>> A.display()
        A
      +-^-+
      B   C
      | +-+-+
      D E F G
    >>> C.display()
       C
     +-+-+
     E F G
    

    In the shortest form,
    How can I "build" an ASCII tree (like above) from the Node class??

    In a longer form,
    The "Logic" of printing is:

    1. When there is only one child, | is put above the child. (D)
    2. Else, Every child has a + above it, (B,C,E,F)
    3. When there are even no. of children, ^ is put below the parent. (A)
    4. Else, (there are odd no. of children) + is put below the parent. (C)

    I have been thinking of starting from below. I realized that there has to be a call to the each of the children, but have been unable to implement anything (of that sorts or otherwise) that gave anything close to it.

    /* Package hub provides primitives for working with the publish-subscribe messaging model. All the types are Go channels, so the usage is identical to theirs. The pattern is simple: publish messages to given topics. To do this a series of commands are sent to the Hub, which is a plain channel, commands that are executed afterwards. Most commands take topics as parameters, but if the topics are not specified a default topic (a topic identified by the nil interface) is used. */ package hub type ( // Hub is the coordinator channel on which commands are sent. Even though in general // channels don't have to be closed, the Hub must be, or resources will be leaked otherwise. Hub chan interface{} // Conn is a connection. It is a channel on which the Hub sends messages // from each Topic the Conn is connected to. // // Message a Conn as a command and the Hub will connect it to the default topic. Conn chan interface{} // Topic is an identifier for a topic. Topic interface{} // Number is an alias for int. If a struct field of a command that manipulates a connections has this type, // it means that the first time the command is sent negative values are ignored, // and on subsequent times negative values do not reset specific properties of // the connections that the respective values manipulate. Number = int // TopicConn represents a connection to a topic. Use it with ConnectEach // to describe how the connection connects to topics. TopicConn struct { Topic Topic // The number of messages the connection should receive from the given topic. // If the ConnectEach command is sent multiple times for the same connection, // the number of messages is reset to the new value. MessageCount Number } Cannot start wcf service host

    I'm trying to create a service host for my WCF application. When I start the app I get an error saying

    The service cannot be started. This service has no endpoint defined. Please add at least one endpoint for the service in config file and try again.

    I followed the tutorial on PluralSight and this is the code I came up with

    using System.ServiceModel;
    using FreedomService;
    
    namespace ConsoleHost
    {
        class Program
        {
            static void Main(string[] args)
            {
                var host = new ServiceHost(typeof(PeopleService));
                host.AddServiceEndpoint(typeof (IPeopleService), new BasicHttpBinding(),
                                        "http://localhost:8080/people/basic");
                host.AddServiceEndpoint(typeof(IPeopleService), new WSHttpBinding(), 
                                        "http://localhost:8080/people/ws");
                host.AddServiceEndpoint(typeof(IPeopleService), new NetTcpBinding(), 
                                        "net.tcp://localhost:8081/people");
                try
                {
                    host.Open();
                    PrintServiceInfo(host);
                    Console.ReadLine();
                    host.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    host.Abort();
                }
            }
    
            static void PrintServiceInfo(ServiceHost host)
            {
                Console.WriteLine("{0} is up and running with these endpoints:",host.Description.ServiceType);
                foreach (var endpoint in host.Description.Endpoints)
                {
                    Console.WriteLine(endpoint.Address);
                }
            }
    
        }
    }
    

    IPeopleService.cs

    [ServiceContract]
    public interface IPeopleService
    {
        [OperationContract]
        string GetData(int value);
    
        [OperationContract]
        PersonType GetPersonById(int id);
    }
    

    PeopleService.cs

    public class PeopleService : IPeopleService, IDisposable
        {
            private ICollection<PersonType> People = new Collection<PersonType>
                {
                    //...
                };
            public string GetData(int value)
            {
                return string.Format("You entered: {0}", value);
            }
    
            public PersonType GetPersonById(int id)
            {
                var person = People.First(p => p.Id == id);
                if (person!= null)
                    return person;
                throw new InvalidDataException(string.Format("No Person with the id: {0} found.",id));
            }
    
            public void Dispose()
            {
                this.People = null;
            }
        }
    

    app.config

    import numpy as np from numpy import (reciprocal, einsum, maximum, minimum, zeros_like, atleast_1d, squeeze) from scipy.linalg import eig, eigvals, matrix_balance, norm from harold._classes import Transfer, transfer_to_state from harold._discrete_funcs import discretize from harold._arg_utils import _check_for_state, _check_for_state_or_transfer __all__ = ['simulate_linear_system', 'simulate_step_response', 'simulate_impulse_response'] def simulate_linear_system(sys, u, t=None, x0=None, per_channel=False): """ Compute the linear model response to an input array sampled at given time instances. Parameters ---------- sys : {State, Transfer} The system model to be simulated u : array_like The real-valued input sequence to force the model. 1D arrays for single input models and 2D arrays that has as many columns as the number of inputs are valid inputs. t : array_like, optional The real-valued sequence to be used for the evolution of the system. The values should be equally spaced otherwise an error is raised. For discrete time models increments different than the sampling period also raises an error. On the other hand for discrete models this can be omitted and a time sequence will be generated automatically. x0 : array_like, optional The initial condition array. If omitted an array of zeros is assumed. Note that Transfer models by definition assume zero initial conditions and will raise an error. per_channel : bool, optional If this is set to True and if the system has multiple inputs, the response of each input is returned individually. For example, if a system has 4 inputs and 3 outputs then the response shape becomes (num, p, m) instead of (num, p) where k-th slice (:, :, k) is the response from the k-th input channel. For single input systems, this keyword has no effect. Returns ------- yout : ndarray The resulting response array. The array is 1D if sys is SISO and has p columns if sys has p outputs. tout : ndarray The time sequence used in the simulation. If the parameter t is not None then a copy of t is given. Notes ----- For Transfer models, first conversion to a state model is performed and then the resulting model is used for computations. """ _check_for_state_or_transfer(sys) -- Organiation role rights create table o_org_role_to_right ( id number(20) generated always as identity, creationdate timestamp not null, o_role varchar(255) not null, o_right varchar(255) not null, fk_organisation number(20) not null, primary key (id) ); alter table o_org_role_to_right add constraint org_role_to_right_to_org_idx foreign key (fk_organisation) references o_org_organisation (id); create index idx_org_role_to_r_to_org_idx on o_org_role_to_right(fk_organisation); -- Lectures alter table o_lecture_reason add l_enabled number default 1 not null; -- Absences alter table o_lecture_absence_category add l_enabled number default 1 not null; -- Contact tracing create table o_ct_location ( id number(20) generated always as identity, creationdate date not null, lastmodified date not null, l_reference varchar2(255), l_titel varchar2(255), l_room varchar2(255), l_building varchar2(255), l_sector varchar2(255), l_table varchar2(255), l_qr_id varchar2(255) not null, l_qr_text varchar2(4000), l_guests number default 1 not null, l_printed number default 0 not null, unique(l_qr_id), primary key (id) ); create table o_ct_registration ( id number(20) generated always as identity, creationdate date not null, l_deletion_date date not null, l_start_date date not null, l_end_date date, l_nick_name varchar2(255), l_first_name varchar2(255), l_last_name varchar2(255), l_street varchar2(255), l_extra_line varchar2(255), l_zip_code varchar2(255), l_city varchar2(255), l_email varchar2(255), l_institutional_email varchar2(255), l_generic_email varchar2(255), l_private_phone varchar2(255), l_mobile_phone varchar2(255), l_office_phone varchar2(255), fk_location number(20) not null, primary key (id) ); alter table o_ct_registration add constraint reg_to_loc_idx foreign key (fk_location) references o_ct_location (id); create index idx_reg_to_loc_idx on o_ct_registration (fk_location); // Copyright (c) 2011-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "sendcoinsdialog.h" #include "ui_sendcoinsdialog.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "coincontroldialog.h" #include "guiutil.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "walletmodel.h" #include "base58.h" #include "coincontrol.h" #include "ui_interface.h" #include #include #include SendCoinsDialog::SendCoinsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SendCoinsDialog), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); #endif GUIUtil::setupAddressWidget(ui->lineEditCoinControlChange, this); addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // Coin Control connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int))); connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString &)), this, SLOT(coinControlChangeEdited(const QString &))); Maria Sorvillo is an Italian football defender, currently playing for UPC Tavagnacco in Italy's Serie A. She has won five leagues with SS Lazio, CF Bardolino and Torres CF. She has been a member of the Italian national team. References 1982 births Living people Italian women's footballers Italy women's international footballers Serie A (women's football) players SS Lazio Women 2015 players Torres Calcio Femminile players A.S.D. AGSM Verona F.C. players ASD UPC Tavagnacco players Women's association football defenders Torino Women A.S.D. players Roma CF players People from Aversa Footballers from the Province of Caserta __all__ = ("group_attempts", "fails_filter", "reduce_to_failures",) def group_attempts(sequence, filter_func=None): if filter_func is None: filter_func = lambda x:True last, l = None, [] for x in sequence: if isinstance(x, tuple) and x[0] == 'inspecting': if l: yield last, l last, l = x[1], [] elif last is not None: if filter_func(x): # inline ignored frames if getattr(x, 'ignored', False): l.extend(y for y in x.events if filter_func(y)) else: l.append(x) if l: yield last, l def fails_filter(x): if not isinstance(x, tuple): return not x.succeeded if x[0] == "viable": return not x[1] return x[0] != "inspecting" def reduce_to_failures(frame): if frame.succeeded: return [] l = [frame] for pkg, nodes in group_attempts(frame.events, fails_filter): l2 = [] for x in nodes: if not isinstance(x, tuple): l2.append(reduce_to_failures(x)) else: l2.append(x) l.append((pkg, l2)) return l Nested classes' scope?

    I'm trying to understand scope in nested classes in Python. Here is my example code:

    class OuterClass:
        outer_var = 1
        class InnerClass:
            inner_var = outer_var
    

    The creation of class does not complete and I get the error:

    <type 'exceptions.NameError'>: name 'outer_var' is not defined
    

    Trying inner_var = Outerclass.outer_var doesn't work. I get:

    <type 'exceptions.NameError'>: name 'OuterClass' is not defined
    

    I am trying to access the static outer_var from InnerClass.

    Is there a way to do this?

    How to add TemplateField to a gridview in the code behind?

    I have a DropDownList which has a list of tables. Under it there is GridView. Based on the table selected from the drop down list box, I will populate the GridView dynamically. Since the tables could have different column names, I need to create the template field for the GridView dynamically.

    Following is my bind method. I have two problems:

    1. I couldn’t wrap the binding part in if (!IsPostBack) since the GridView is populated based on the selection of the DropDownList, so everytime I change the selection, the columns will be duplicated.
    2. And I don’t have any data, I think I need to set ItemTemplate of the tField (TemplateField), but how do I do that?

    My bind method

    private void BindGridView()
    {
        DataSet ds = new DataSet();
    
        try
        {
            ds = …
            if (ds.Tables.Count > 0)
            {
    
                foreach (DataColumn dc in ds.Tables[0].Columns)
                {
                    TemplateField tField = new TemplateField();
                    tField.HeaderText = dc.ColumnName;
                    GridView2.Columns.Add(tField);
                }    
    
                GridView2.DataSource = ds.Tables[0];
                GridView2.DataBind();
            }
            else
            {
                …
            }
        }
        catch (Exception ex)
        {
            …    
        }
    }
    
    begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|activemq operator|. name|advisory package|; end_package begin_import import|import name|org operator|. name|apache operator|. name|activemq operator|. name|broker operator|. name|region operator|. name|virtual operator|. name|CompositeDestination import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|activemq operator|. name|broker operator|. name|region operator|. name|virtual operator|. name|VirtualDestination import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|activemq operator|. name|broker operator|. name|region operator|. name|virtual operator|. name|VirtualTopic import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|activemq operator|. name|command operator|. name|ActiveMQDestination import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|activemq operator|. name|command operator|. name|ActiveMQQueue import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|activemq operator|. name|filter operator|. name|DestinationFilter import|; end_import begin_comment comment|/** * This class will use a destination filter to see if the activeMQ destination matches * the given virtual destination * */ end_comment Higher order functions in C

    Is there a "proper" way to implement higher order functions in C.

    I'm mostly curious about things like portability and syntax correctness here and if there are more than one ways what the merits and flaws are.

    Edit: The reason I want to know how to create higher order functions are that I have written a system to convert PyObject lists (which you get when calling python scripts) into a list of C structures containing the same data but organized in a way not dependant on the python.h libraries. So my plan is to have a function which iterates through a pythonic list and calls a function on each item in the list and places the result in a list which it then returns.

    So this is basically my plan:

    typedef gpointer (converter_func_type)(PyObject *)
    
    gpointer converter_function(PyObject *obj)
    {
        // do som stuff and return a struct cast into a gpointer (which is a void *)
    }
    
    GList *pylist_to_clist(PyObject *obj, converter_func_type f)
    {
       GList *some_glist;
       for each item in obj
       {
           some_glist = g_list_append(some_glist, f(item));
       }
       return some_glist;
    }
    
    void some_function_that_executes_a_python_script(void)
    {
       PyObject *result = python stuff that returns a list;
       GList *clist = pylist_to_clist(result, converter_function);
    }
    

    And to clearify the question: I want to know how to do this in safer and more correct C. I would really like to keep the higher order function style but if that is frowned upon I greatly appreciate ways to do this some other way.

    mod get; mod utils; use async_std::task; use chrono::{Duration, NaiveDate, NaiveDateTime, NaiveTime, Weekday}; use get::get_html; use scraper::{Html, Selector}; use std::error::Error; use std::str::FromStr; use tide::{http::Mime, Request, Response, StatusCode}; use utils::{get_period_time, parse_list_uint, parse_weekday, to_ics}; use std::collections::HashMap; fn main() { task::block_on(async { let mut app = tide::new(); app.at("/").get(|_| async { let mut res = Response::new(StatusCode::Accepted); res.set_content_type(tide::http::mime::HTML); res.set_body(include_str!("index.html")); Ok(res) }); app.at("/ics/*").get(|req: Request<()>| async move { let info: String = req.url().path().replace("/ics/", ""); if info.find('_').is_some() { let vec = info.split('_').collect::>(); let content = process(&vec[0].to_uppercase(), &vec[1]).await; let content = to_ics(content.unwrap_or(Vec::new())); let mut res = Response::new(StatusCode::Accepted); res.set_content_type(Mime::from_str("text/calendar").unwrap()); res.set_body(content); Ok(res) } else { Ok("Example CT010101_Passwd".into()) } }); app.at("/json/*").get(|req: Request<()>| async move { let path = req.url().path().replace("/json/", ""); let (usr, pwd) = path.split_at(path.find('/').unwrap_or(0)); let pwd: String = pwd[1..].to_string(); let vec = process(&usr.to_uppercase(), &pwd).await.unwrap_or(Vec::new()); let doc = vec.iter() .map(|dat| dat.to_map()) .collect::>>(); let mut res = Response::new(StatusCode::Accepted); res.set_content_type(Mime::from_str("application/json")?); res.set_body(tide::Body::from_json(&doc)?); Ok(res) }); let port = std::env::var("PORT").unwrap_or("8080".to_string()); app.listen(format!("0.0.0.0:{}", port)).await.unwrap(); }); } async fn process(usr: &str, pwd: &str) -> Result, Box> { let vec = parse_html(get_html(usr, pwd).await?)?; Ok(vec.iter() .map(|(cl, ts, ps)| Data::parse(cl, ts, ps)) .flatten() .collect()) } #[derive(Debug)] pub struct Data { class: String, time_begin: NaiveDateTime, time_end: NaiveDateTime, place: String, } # 返回D^{-0.5}SD^{-0.5}的coords, data, shape,其中S=A+I adj_norm = preprocess_graph(adj) adj_label = adj_train + sp.eye(adj_train.shape[0]) # adj_label = sparse_to_tuple(adj_label) adj_label = torch.FloatTensor(adj_label.toarray()).to(DEVICE) ''' 注意,adj的每个元素非1即0。pos_weight是用于训练的邻接矩阵中负样本边(既不存在的边)和正样本边的倍数(即比值),这个数值在二分类交叉熵损失函数中用到, 如果正样本边所占的比例和负样本边所占比例失衡,比如正样本边很多,负样本边很少,那么在求loss的时候可以提供weight参数,将正样本边的weight设置小一点,负样本边的weight设置大一点, 此时能够很好的平衡两类在loss中的占比,任务效果可以得到进一步提升。参考:https://www.zhihu.com/question/383567632 负样本边的weight都为1,正样本边的weight都为pos_weight ''' pos_weight = float(adj.shape[0] * adj.shape[0] - num_edges) / num_edges norm = adj.shape[0] * adj.shape[0] / float((adj.shape[0] * adj.shape[0] - adj.sum()) * 2) # create model print('create model ...') model = NHGATModelGAN(num_features, hidden_dim1=hidden_dim1, hidden_dim2=hidden_dim2, hidden_dim3=hidden_dim3, num_heads=num_heads, dropout=dropout, alpha=alpha, vae_bool=vae_bool) # define optimizer if optimizer_name == 'adam': optimizer = define_optimizer.define_optimizer_adam(model, lr=lr, weight_decay=weight_decay) elif optimizer_name == 'adamw': optimizer = define_optimizer.define_optimizer_adamw(model, lr=lr, weight_decay=weight_decay) elif optimizer_name == 'sgd': optimizer = define_optimizer.define_optimizer_sgd(model, lr=lr, momentum=momentum, weight_decay=weight_decay) elif optimizer_name == 'adagrad': optimizer = define_optimizer.define_optimizer_adagrad(model, lr=lr, lr_decay=lr_decay, weight_decay=weight_decay) elif optimizer_name == 'rmsprop': optimizer = define_optimizer.define_optimizer_rmsprop(model, lr=lr, weight_decay=weight_decay, momentum=momentum) elif optimizer_name == 'adadelta': optimizer = define_optimizer.define_optimizer_adadelta(model, lr=lr, weight_decay=weight_decay) else: raise NameError('No define optimization function name!') Apache Camel failed to create endpoint

    I'm new on Apache Camel and I need to integrate it with Apache ActiveMQ.

    I tried a basic example, I installed on my computer FileZilla Server and ActiveMQ (works both) and I want to copy a file from the local server to the JMS queue that I created in Active MQ; the problem is that the method start() of CamelContext throws org.apache.camel.FailedToCreateRouteException

    Here is my code (the address in ftpLocation is the static address of my computer):

    import javax.jms.ConnectionFactory;
    
    import org.apache.activemq.ActiveMQConnection;
    import org.apache.activemq.ActiveMQConnectionFactory;
    import org.apache.camel.CamelContext;
    import org.apache.camel.Exchange;
    import org.apache.camel.Processor;
    import org.apache.camel.builder.RouteBuilder;
    import org.apache.camel.component.jms.JmsComponent;
    import org.apache.camel.impl.DefaultCamelContext;
    
    public class FtpToJmsExample
    {
    
        private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;
        private static String ftpLocation = "ftp://192.168.1.10/incoming?username=Luca&password=Luca";
    
        public void start() throws Exception
        {
            CamelContext context = new DefaultCamelContext();
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
            context.addComponent("jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
    
            context.addRoutes( 
                    new RouteBuilder() {
                        public void configure() 
                        {
                            from(ftpLocation).
                            process(executeFirstProcessor()).
                            to("jms:TESTQUEUE");             
                        }
                    });
    
            System.out.println("START");
            context.start();
    
            System.out.println("wait");
            System.out.println(loaded);
    
            Thread.sleep(3000);
    
            while (loaded == false) 
            { 
                System.out.println("in attesa\n");
            }
    
            context.stop();
    
            System.out.println("stop context!");
            System.out.println(loaded);
        }
    
        public static void main(String args[]) throws Exception
        {
            FtpToJmsExample example = new FtpToJmsExample();
            example.start();
        }
    
        private Processor executeFirstProcessor() 
        {
            return new Processor() {
                @Override
                public void process(Exchange exchange) 
                {
                    System.out.println("We just downloaded : "+ 
                            exchange.getIn().getHeader("CamelFileName"));
                    loaded = true;
                }
            };
        }
    }
    

    This is the POM.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    
    Dynamic choices field in Django Models
    
    

    My models.py:

    SHOP1_CHOICES = (
        ('Food Court', 'Food Court'),
        ('KFC', 'KFC'),
    
    )
    
    SHOP2_CHOICES = (
        ('Sports Arena', 'Sports Arena'),
        ('Disco D', 'Disco D'),
    
    )
    
    SHOP3_CHOICES = (
        ('Bowling Arena', 'Bowling Arena'),
        ('Cinemax', 'Cinemax'),
    
    )
    
    class Feed(models.Model):
      gender = models.CharField(max_length=5, choices=GENDER_CHOICES, default='girl')
      name =models.CharField(max_length=25)
      shop=models.CharField(max_length=20)
      location=models.CharField(max_length=25, choices=SHOP1_CHOICES)
    

    Here if Feed.shop == 'shop1' I want to load SHOP1_CHOICES on Feed.location. Currently irrespective of what shop, it just displays the SHOP1_CHOICES (no surprise).How can I implement it? I am stuck, please help.

    Failed to load resource: the server responded with a status of 404 (NOT FOUND)

    I am uisng python,To display data from json file to a page,i am getting the below errors

    Failed to load resource: the server responded with a status of 404 (NOT FOUND) http://localhost:8000/static/script/jquery-1.9.1.min.js
    Failed to load resource: the server responded with a status of 404 (NOT FOUND) http://localhost:8000/static/script/myscript.js
    

    myscript.js file

    $("#button").click(function(){
        $.getJSON("item.json",function(obj){
           $.each(obj,function(key,value){
              $("ul").append("<li>+value.item1+"</li>");
              $("ul").append("<li>+value.item2+"</li>");
              $("ul").append("<li>+value.item3+"</li>");
           });
        });
    }); 
    

    .json file is

    {
    "p1":{
          "item1":"apple",
          "item2":"orange",
          "item3":"banana",
          },
    "p2":{
          "item1":"water",
          "item2":"milk",
          "item3":"alcohol",
         }
    }
    

    template is

    <html>
        <head>
        <body>
        <ul></ul>
        <button></button>
        <script src="script/jquery-1.9.1,min.js" type="text/javascript"></script>
        <script src="script/myscript.js" type="text/javascript"></script>
        </body>
        </head>
    </html>
    

    1).js file is in my project folder and path also setted.

    2).I am not doing any query in my views.py,as i am new to this i am confused with this.So any codings need to perform in the views.py for fetching the data from json.

    3).Not able to sort out the above errors,please provide me the possible reason so that i can run this function.

    Thanks

    // Copyright (C) 2017 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.index.group; import com.google.common.collect.ImmutableSet; import com.google.gerrit.index.IndexConfig; import com.google.gerrit.index.query.FieldBundle; import com.google.gerrit.reviewdb.client.AccountGroup; import com.google.gerrit.reviewdb.client.RefNames; import com.google.gerrit.server.config.AllUsersName; import com.google.gerrit.server.git.GitRepositoryManager; import com.google.inject.Inject; import com.google.inject.Singleton; import java.io.IOException; import java.util.Optional; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; /** * Checks if documents in the group index are stale. * *

    An index document is considered stale if the stored SHA1 differs from the HEAD SHA1 of the * groups branch. * *

    Note: This only applies to NoteDb. */ @Singleton public class StalenessChecker { public static final ImmutableSet FIELDS = ImmutableSet.of(GroupField.UUID.getName(), GroupField.REF_STATE.getName()); private final GroupIndexCollection indexes; private final GitRepositoryManager repoManager; private final IndexConfig indexConfig; private final AllUsersName allUsers; @Inject StalenessChecker( GroupIndexCollection indexes, GitRepositoryManager repoManager, IndexConfig indexConfig, AllUsersName allUsers) { this.indexes = indexes; this.repoManager = repoManager; this.indexConfig = indexConfig; this.allUsers = allUsers; } public boolean isStale(AccountGroup.UUID uuid) throws IOException { GroupIndex i = indexes.getSearchIndex(); if (i == null) { return false; // No index; caller couldn't do anything if it is stale. } Optional result = i.getRaw(uuid, IndexedGroupQuery.createOptions(indexConfig, 0, 1, FIELDS)); if (!result.isPresent()) { // The document is missing in the index. try (Repository repo = repoManager.openRepository(allUsers)) { Ref ref = repo.exactRef(RefNames.refsGroups(uuid)); // Stale if the group actually exists. return ref != null; } } ### User: my tauri app fails to build on windows: LINK : fatal error LNK1181: cannot open input file 'WebView2Loader.dll.lib' ### Assistant: Classic WebView2 linking issue with Tauri on Windows. Usually one of these fixes it: 1. Make sure the Microsoft Edge WebView2 Runtime is installed, plus the "C++ Build Tools" workload in Visual Studio Installer (you need the MSVC toolchain, not MinGW). 2. Clear the build cache: delete `src-tauri/target` and rebuild — a stale artifact from an older `webview2-com-sys` often lingers there. 3. Check that Rust targets MSVC: `rustup default stable-x86_64-pc-windows-msvc`. 4. In CI, confirm the runner is `windows-latest` and consider the `webview2-com/static` feature in Cargo.toml for static linking. Most of the time it's #2: a poisoned target cache after a toolchain update. # Estimation of the variance when sigma2 is unspecified if sigma2 is None: xubar = (1 + tauubar) * (1 + alpha / tauubar) eH_ub = int(np.min([np.ceil(L / (1 + alpha)) - 1, H])) - 1 # upper_bound = (np.sum(s**2)+residual)/(L*M) # lower_bound = np.max( # [s[eH_ub+1]**2/(M*xubar), np.mean(s[eH_ub+1:]**2)/M]) upper_bound = (torch.sum(s**2) + residual) / (L * M) lower_bound = torch.max(torch.stack( [s[eH_ub + 1]**2 / (M * xubar), torch.mean(s[eH_ub + 1:]**2) / M], dim=0)) scale = 1. # /lower_bound s = s * np.sqrt(scale) residual = residual * scale lower_bound = lower_bound * scale upper_bound = upper_bound * scale sigma2_opt = minimize_scalar( EVBsigma2, args=(L, M, s.cpu().numpy(), residual, xubar), bounds=[lower_bound.cpu().numpy(), upper_bound.cpu().numpy()], method='Bounded') sigma2 = sigma2_opt.x # Threshold gamma term threshold = np.sqrt(M * sigma2 * (1 + tauubar) * (1 + alpha / tauubar)) # pos = np.sum(s > threshold) pos = torch.sum(s > threshold) # Formula (15) from [2] # d = torch.multiply(s[:pos]/2, # 1-torch.divide( # torch.tensor((L+M)*sigma2, device=s.device), # s[:pos]**2) + torch.sqrt((1-torch.divide( # torch.tensor( # (L+M)*sigma2, device=s.device), # s[:pos]**2))**2 - # 4*L*M*sigma2**2/s[:pos]**4)) # d = np.multiply(s[:pos]/2, 1-np.divide((L+M)*sigma2, s[:pos]**2) + np.sqrt( # (1-np.divide((L+M)*sigma2, s[:pos]**2))**2 - 4*L*M*sigma2**2/s[:pos]**4)) d = (s[:pos] / 2) * (1 - (L + M) * sigma2 / s[:pos]**2 + torch.sqrt((1 - (L + M) * sigma2 / s[:pos]**2)**2 - 4 * L * M * sigma2**2 / s[:pos]**4)) # Computation of the posterior # post = {} # post['ma'] = np.zeros(H) # post['mb'] = np.zeros(H) # post['sa2'] = np.zeros(H) # post['sb2'] = np.zeros(H) # post['cacb'] = np.zeros(H) # tau = np.multiply(d, s[:pos])/(M*sigma2) # delta = np.multiply(np.sqrt(np.divide(M*d, L*s[:pos])), 1+alpha/tau) # post['ma'][:pos] = np.sqrt(np.multiply(d, delta)) # post['mb'][:pos] = np.sqrt(np.divide(d, delta)) # post['sa2'][:pos] = np.divide(sigma2*delta, s[:pos]) # post['sb2'][:pos] = np.divide(sigma2, np.multiply(delta, s[:pos])) # post['cacb'][:pos] = np.sqrt(np.multiply(d, s[:pos])/(L*M)) # post['sigma2'] = sigma2 # post['F'] = 0.5*(L*M*np.log(2*np.pi*sigma2) + # (residual+np.sum(s**2))/sigma2 + np.sum( # M*np.log(tau+1) + L*np.log(tau/alpha + 1) - M*tau)) return U[:, :pos], torch.diag(d), V[:, :pos] # , post def EVBsigma2(sigma2, L, M, s, residual, xubar): H = len(s) alpha = L / M x = s**2 / (M * sigma2) SSIS (ASCII needed): "Code page is 1252 and is required to be 20127"

    I have a requirement to export a database to a tab-delimited file in the ASCII format. I am using derived columns to convert any Unicode strings to non-Unicode strings. For example, a former Unicode text stream is now casted as this:

    (DT_TEXT,20127)incomingMessage
    

    But SSIS is still looking for ANSI. I am still seeing an error at the Flat File Destination:

    The code page on input column <column_name> is 1252 and is required to be 20127.
    

    This happens for any column in the table, not just Unicode ones.

    This is what I have been doing to ensure ASCII is used:

    • In the Flat File Connection Manager, used Code page "20127 (US-ASCII)"
    • Used a Derived Column to cast data types
    • In the OLE DB source, set the default code page to 20127

    Any thoughts?

    ### User: Why does my Node server leak memory when I attach a listener inside the request handler? app.get('/data', (req, res) => { emitter.on('update', (d) => res.write(JSON.stringify(d))); ... }); ### Assistant: Because every request adds a **new** listener to a long-lived emitter and nothing ever removes it. The emitter holds references to the closure, which holds `res`, which holds the socket and buffers — none of it can be garbage-collected, and the listener array grows forever (you'll also see the MaxListenersExceededWarning). Fix: remove the listener when the response ends. ```javascript app.get('/data', (req, res) => { const onUpdate = (d) => res.write(JSON.stringify(d)); emitter.on('update', onUpdate); res.on('close', () => emitter.off('update', onUpdate)); }); ``` Rule of thumb: any `.on()` targeting an object that outlives the current scope needs a matching `.off()` on a well-defined lifecycle event. let current_cpu = fdt.cpus().find(|cpu| cpu.ids().first() == hart_id).unwrap(); let timebase_frequency = current_cpu.timebase_frequency(); TIMER_FREQ.store(timebase_frequency, Ordering::Relaxed); let mut stdout_interrupts = None; let stdout = fdt.chosen().stdout(); if let Some((node, reg, compatible)) = stdout.and_then(|n| Some((n, n.reg()?.next()?, n.compatible()?))) { let stdout_addr = reg.starting_address as *mut u8; if let Some(device) = crate::io::ConsoleDevices::from_compatible(compatible) { let stdout_phys = PhysicalAddress::from_ptr(stdout_addr); let ptr = phys2virt(stdout_phys); unsafe { device.set_raw_console(ptr.as_mut_ptr()) }; if let Some(interrupts) = node.interrupts() { // Try to get stdout loaded ASAP, so register interrupts later // on if there are any stdout_interrupts = Some((device, interrupts, ptr)); } } } let mut init_path = "init"; if let Some(args) = fdt.chosen().bootargs() { let split_args = args.split(' ').map(|s| { let mut parts = s.splitn(2, '='); (parts.next().unwrap(), parts.next()) }); for (option, value) in split_args { match option { "log-filter" => io::logging::parse_log_filter(value), "init" => match value { Some(path) => init_path = path, None => log::warn!("No path provided for init process! Defaulting to `init`"), }, "no-color" | "no-colour" => io::logging::USE_COLOR.store(false, Ordering::Relaxed), "console" => match value { Some("sbi") => { if let ExtensionAvailability::Available(_) = probe_extension(sbi::legacy::CONSOLE_PUTCHAR_EID) { let this_is_awful = Box::leak(Box::new(io::LegacySbiConsoleOut)); io::set_console(this_is_awful); } } Some(fdt_node) => { if let Some((node, reg, compatible)) = fdt.find_node(fdt_node).and_then(|n| Some((n, n.reg()?.next()?, n.compatible()?))) { let stdout_addr = reg.starting_address as *mut u8; if let Some(device) = crate::io::ConsoleDevices::from_compatible(compatible) { let stdout_phys = PhysicalAddress::from_ptr(stdout_addr); let ptr = phys2virt(stdout_phys); unsafe { device.set_raw_console(ptr.as_mut_ptr()) }; ### User: Write a Python function that returns the median of a list. Handle the empty-list case. ### Assistant: Here's a version with edge cases handled: ```python def median(values: list[float]) -> float: """Return the median of a list of numbers. Raises ValueError for an empty list. """ if not values: raise ValueError("median() arg is an empty list") ordered = sorted(values) n = len(ordered) mid = n // 2 if n % 2 == 1: return float(ordered[mid]) return (ordered[mid - 1] + ordered[mid]) / 2.0 ``` For an even count it averages the two middle elements. If your input may contain NaN, filter with `math.isnan` before sorting — otherwise the comparison order breaks. Leaflet: Add a link to the markers

    Pretty simple question: How can I make the map markers in Leaflet clickable and route the user to an other page? Every marker has its own page.

    I've tried the following without success; somehow all the markers point to the same page, which is the last assigned URI.

    var markers = [
        { coords: [51.505, -0.09], uri: '/some-page' },
        ...
    ];
    
    for(x in markers)
    {
        L.marker(markers[x].coords).on('click', function() {
            window.location = markers[x].uri;
        }).addTo(map);
    }
    

    This issue is really driving me nuts.

    import clone from 'clone'; import uuid from 'uuid/v4'; import Vue from 'vue'; import Vuex from 'vuex'; import { RunData, RunDataPlayer, RunDataTeam } from '../../../types'; import { msToTimeStr } from '../_misc/helpers'; import { store as repStore } from '../_misc/replicant-store'; Vue.use(Vuex); enum Mode { New = 'New', EditActive = 'EditActive', EditOther = 'EditOther', Duplicate = 'Duplicate', } const defaultRunData: RunData = { teams: [], customData: {}, id: uuid(), }; const defaultTeam: RunDataTeam = { id: uuid(), players: [], }; const defaultPlayer: RunDataPlayer = { id: uuid(), teamID: '', name: '', social: {}, }; export default new Vuex.Store({ state: { runData: clone(defaultRunData), mode: 'New' as Mode, prevID: undefined as string | undefined, updateTwitch: false, }, mutations: { updateRunData(state, { value }): void { Vue.set(state, 'runData', clone(value)); Vue.set(state, 'updateTwitch', false); }, updateMode(state, { value }): void { Vue.set(state, 'mode', value); }, updateTwitch(state, { value }): void { Vue.set(state, 'updateTwitch', value); }, setAsDuplicate(state): void { Vue.set(state, 'prevID', state.runData.id); Vue.set(state.runData, 'id', uuid()); }, setPreviousRunID(state, { value }): void { Vue.set(state, 'prevID', value); }, resetRunData(state): void { Vue.set(state, 'runData', clone(defaultRunData)); if (repStore.state.defaultSetupTime) { // Fill in default setup time if available. Vue.set(state.runData, 'setupTimeS', repStore.state.defaultSetupTime); Vue.set(state.runData, 'setupTime', msToTimeStr( repStore.state.defaultSetupTime * 1000, )); } Vue.set(state.runData, 'id', uuid()); Vue.set(state, 'updateTwitch', false); }, addNewTeam(state): void { const teamData = clone(defaultTeam); teamData.id = uuid(); // Adds an empty player as well for ease of use. const playerData = clone(defaultPlayer); playerData.id = uuid(); playerData.teamID = teamData.id; teamData.players.push(playerData); How to install Delphi 7 on Vista

    I tried to install Delphi 7 on Vista several times and Vista prevented me from doing so by telling me that there are known problems with this application (Delphi 7). Several other people in my company experienced problems with installing D7 on Vista.

    This lead to the conclusion that we were at risk with our D7 application, as the company could within the lifetime of the app switch to Vista or Windows 7 and newer Delphi versions are not in the policy of the company. Therefore management decided on rewriting the app in C#.

    My question(s):

    1. How to install D7 on Vista
    2. Experience with such an installation
    3. Risk assessment concerning stability of IDE and developed programs
    4. Risk assessment concerning executability under Windows 7

    Not using any third party components or database - there should be no problem running the developed app under Vista. If not able to develop and debug under Vista (which at the point being will be the only customer platform, yes, internal programming) will result in a sort of cross platform development - if we would be allowed to keep XP as the development platform.

    It is not a developers decision to rewrite, it has been done in the company for the last 3 years: if you had to significantly touch an app developed in Delphi or if there was a certain risk of it not to survive the planned life circle/life span, it had to be rewritten. The life cycle just expanded to 2015 due to canceling another project.

    So the main issue here would really be: I would like to have educated arguments about the risks.

    The Teahouse, about an immigrant restaurant owner trying to protect his family from juvenile gangs, takes a scathing look at the criminal justice system in Hong Kong and is considered one of Kuei's landmark works. The film is also a strong example of Kuei's penchant for eschewing studio sets for the realistic immediacy of urban locations, vividly depicting the harsh environment of lower-class immigrant life. It was followed by a hit sequel in 1975, Big Brother Cheng, with kung fu star Kuan Tai Chen reprising the eponymous role. Kuei transcended the tired revenge tropes of many action sequels, making Big Brother Cheng a compelling and uncompromising examination of crime, juvenile delinquency and social injustice. Though Kuei's contributions to Hong Kong cinema have often been neglected in recent decades, one film in particular ensured that he would enjoy a devoted cult audience for many years to come. Reaching new extremes in graphic sex and violence, the horror movie The Killer Snakes, is still considered one of Kuei's most notorious and controversial pictures. The plot centers on a young man's special powers with venomous snakes, which allow him to take revenge on those who have wronged him. Several over-the-top scenes of S&M sex and of course lethal snake attacks earned The Killer Snakes its following as a midnight movie classic and to some degree, cemented Kuei's reputation as a maverick filmmaker. The movie is also noteworthy for actor Kam Kwok-Leung's crazily committed performance and the use of hundreds of live poisonous snakes. Kuei continued to challenge himself by directing segments for The Criminals film series, an acclaimed anthology based on actual Hong Kong cases. His episodes (across four films from 1975 to 1977) included "The Deaf Mute Killer," "The Informer" and "Arson". During the late '70s, Kuei also expanded his filmography to include Cantonese-language comedies (Mr. Funnybone, Crazy Imposters, The Reckless Cricket) and kung fu (The Iron Dragon Strikes Back). The 1980s saw the versatile Kuei reinventing himself once again, this time with the popular supernatural fantasy, Hex and its two sequels, Hex vs. Witchcraft and Hex After Hex. The latter contained Kuei's signature social satire, taking on such hot-button topics as real estate development and Hong Kong's looming reunification with China. In fact, an early cut of the 1982 film featured a sequence where a character is branded on his behind with "1997" the year mainland China would resume control over Hong Kong. Deemed too politically sensitive, the scene was re-edited and the branded posterior featured "SB" (for Shaw Brothers) instead. Still, Kuei ingeniously found a way to insert a visual gag at the studio's expense. Kuei also delved into the wuxia genre for the first time with Killer Constable (1980). Though a box-office disappointment at the time of its release, today Killer Constable is considered one of Kuei's finest, most accomplished movies. package consul import ( "context" "errors" "fmt" "math/rand" "net" "net/http" "net/url" "regexp" "strconv" "strings" "sync" "sync/atomic" "time" "github.com/hashicorp/consul/api" log "github.com/hashicorp/go-hclog" "github.com/hashicorp/go-secure-stdlib/parseutil" "github.com/hashicorp/go-secure-stdlib/strutil" "github.com/hashicorp/go-secure-stdlib/tlsutil" "github.com/hashicorp/vault/sdk/helper/consts" sr "github.com/hashicorp/vault/serviceregistration" "github.com/hashicorp/vault/vault/diagnose" atomicB "go.uber.org/atomic" "golang.org/x/net/http2" ) const ( // checkJitterFactor specifies the jitter factor used to stagger checks checkJitterFactor = 16 // checkMinBuffer specifies provides a guarantee that a check will not // be executed too close to the TTL check timeout checkMinBuffer = 100 * time.Millisecond // consulRetryInterval specifies the retry duration to use when an // API call to the Consul agent fails. consulRetryInterval = 1 * time.Second // defaultCheckTimeout changes the timeout of TTL checks defaultCheckTimeout = 5 * time.Second // DefaultServiceName is the default Consul service name used when // advertising a Vault instance. DefaultServiceName = "vault" // reconcileTimeout is how often Vault should query Consul to detect // and fix any state drift. reconcileTimeout = 60 * time.Second // metaExternalSource is a metadata value for external-source that can be // used by the Consul UI. metaExternalSource = "vault" ) var hostnameRegex = regexp.MustCompile(`^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$`) // serviceRegistration is a ServiceRegistration that advertises the state of // Vault to Consul. type serviceRegistration struct { Client *api.Client logger log.Logger serviceLock sync.RWMutex redirectHost string redirectPort int64 serviceName string serviceTags []string serviceAddress *string disableRegistration bool checkTimeout time.Duration notifyActiveCh chan struct{} notifySealedCh chan struct{} notifyPerfStandbyCh chan struct{} notifyInitializedCh chan struct{} isActive *atomicB.Bool isSealed *atomicB.Bool isPerfStandby *atomicB.Bool isInitialized *atomicB.Bool } // NewConsulServiceRegistration constructs a Consul-based ServiceRegistration. func NewServiceRegistration(conf map[string]string, logger log.Logger, state sr.State) (sr.ServiceRegistration, error) { // Allow admins to disable consul integration disableReg, ok := conf["disable_registration"] var disableRegistration bool if ok && disableReg != "" { b, err := parseutil.ParseBool(disableReg) if err != nil { return nil, fmt.Errorf("failed parsing disable_registration parameter: %w", err) } disableRegistration = b } if logger.IsDebug() { logger.Debug("config disable_registration set", "disable_registration", disableRegistration) } java.lang.StackOverflowError when persisting an object jpa

    I am building an application using JPA, JSF, EJB, Derby. At this point the application is still small. I have a form in the application to add new products. When adding data to the db it goes smoothly until I restart the application or the server. When I restart either the server or app I get java.lang.StackOverflowError, I still can query the db for the data represented by the product db, but creation product is not possible. I have only 5 entries in the db, as of now, but I am concerned about this happening so early.

    This is the Ejb (Getter, setter and constructors removed for simplicity):

    @Stateless
    public class ProductEJB{
    
        @PersistenceContext(unitName = "luavipuPU")
        private EntityManager em;
    
        public List<Product> findAllProducts()
        {
            TypedQuery<Product> query = em.createNamedQuery("findAllProducts", Product.class);
            return query.getResultList();
        }
    
        public Product findProductById(int productId)
        {
            return em.find(Product.class, productId);
        }
    
        public Product createProduct(Product product)
        {
            product.setDateAdded(productCreationDate());
            em.persist(product);
            return product;        
        }    
    
        public void updateProduct(Product product)
        {
            em.merge(product);
        }
    
        public void deleteProduct(Product product)
        {
            product = em.find(Product.class, product.getProduct_id());
            em.remove(em.merge(product));
        }
    

    this is the ProductController (Getter, setter and constructors removed for simplicity):

        @Named
    @RequestScoped
    public class ProductController {
    
        @EJB
        private ProductEJB productEjb;
        @EJB
        private CategoryEJB categoryEjb;
    
        private Product product = new Product();
        private List<Product> productList = new ArrayList<Product>();
    
        private Category category;
        private List<Category> categoryList = new ArrayList<Category>();
    
        public String doCreateProduct()
        {
            product = productEjb.createProduct(product);
            productList = productEjb.findAllProducts();
            return "listProduct?faces-redirect=true";
        }
    
        public String doDeleteProduct()
        {
            productEjb.deleteProduct(product);
            return "deleteProduct?faces-redirect=true";
        }
    
        public String cancelDeleteAction()
        {
            return "listProduct?faces-redirect=true";
        }
    
    
        @PostConstruct
        public void init()
        {
            categoryList = categoryEjb.findAllCategory();
            productList = productEjb.findAllProducts();        
        }
    

    Category Entity (Getters, setters, hash() and constructors removed for simplicity):

    import { Random } from '../../random/generator/Random'; import { Arbitrary } from './definition/Arbitrary'; import { Shrinkable } from './definition/Shrinkable'; import { nat } from './IntegerArbitrary'; /** * Constraints to be applied on {@link option} * @remarks Since 2.2.0 * @public */ export interface OptionConstraints { /** * The probability to build a nil value is of `1 / freq` * @remarks Since 1.17.0 */ freq?: number; /** * The nil value (default would be null) * @remarks Since 1.17.0 */ nil?: TNil; } /** @internal */ class OptionArbitrary extends Arbitrary { readonly isOptionArb: Arbitrary; constructor(readonly arb: Arbitrary, readonly frequency: number, readonly nil: TNil) { super(); this.isOptionArb = nat(frequency); // 1 chance over to have non nil } private static extendedShrinkable(s: Shrinkable, nil: TNil): Shrinkable { function* g(): IterableIterator> { yield new Shrinkable(nil); } return new Shrinkable(s.value_ as T | TNil, () => s .shrink() .map((v) => OptionArbitrary.extendedShrinkable(v, nil)) .join(g()) ); } generate(mrng: Random): Shrinkable { return this.isOptionArb.generate(mrng).value === 0 ? new Shrinkable(this.nil) : OptionArbitrary.extendedShrinkable(this.arb.generate(mrng), this.nil); } withBias(freq: number) { return new OptionArbitrary(this.arb.withBias(freq), this.frequency, this.nil); } } ### User: What does this bash do? find . -name '*.log' -mtime +7 -exec rm {} + ### Assistant: It deletes all `.log` files older than seven days, recursively from the current directory. Piece by piece: `find .` walks the tree from here; `-name '*.log'` matches files ending in .log; `-mtime +7` filters to files modified more than 7 full days ago; `-exec rm {} +` runs `rm` on the matches, batching many files per invocation (the `+` terminator) instead of one `rm` per file (which is what `\;` would do — slower). Safety tip: dry-run it first by replacing `-exec rm {} +` with `-print` to see what would be deleted. Error: [$injector:unpr] Unknown provider: modalInstanceProvider <- modalInstance <- modalCtrl with the latest ui bootstrap

    EDIT - as the code below is, the modal will work - my issue was I had included ng-app and ng-controller in my HTML template for my modal, however they are not included in the below question.

    I've my main controller, modal controller and my modal template HTML

    Everything seems to be in order and I cannot for the life of me work out (or find out from stackoverflow) why I keep getting Error: [$injector:unpr] Unknown provider: modalInstanceProvider <- modalInstance <- modalCtrl error. BTW $modal is now depricated, it's $ubiModal now.

    Main ctrl:

    var module = angular.module("app", ["agGrid", "ngAnimate", "ngSanitize", "ngDialog", "ui.bootstrap"])
    
    module.controller("mainCtrl", ["$scope", "dataService", "$timeout", "dateFilter", "ngDialog", "$http", "$uibModal", function ($scope, dataService, $timeout, dateFilter, ngDialog, $http, $uibModal) {
    
    $scope.open = function () {
    
        var uibModalInstance= $uibModal.open({
            templateUrl: "views/Modal.html",
            controller: "modalCtrl",
            show: true,
        })
    };
    }]);
    

    my modal controller:

    module.controller("modalCtrl", ["$scope", "ngDialog", "dataService", "$uibModalInstance", function ($scope, ngDialog, dataService, $uibModalInstance) {
    
    //do stuff
    
    }]);
    

    and my HTML template:

     <div id="loginModal" class="modal show" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" ng-click="closeThisDialog(); printArray()" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                        <h1 class="text-center" style="text-align: center">Entities:</h1>
                    </div>
                    <div class="modal-body">
    
                        <div>
                            <div>
                                <input type="text" placeholder="Search" ng-model="entity">
                            </div>
                        </div>
    
                        <div ng-repeat="entity in entityArray | filter:entity">
    
                            <label>
                                <input style="float: left; margin-top: 5px" type="checkbox" ng-model="entityChecked" ng-change="getEntityFromModal(entity, entityChecked)" />
                                <span>{{entity}}</span>
                            </label>
                        </div>
                    </div>
                    <button ng-click="okButtonEntity();" >OK</button>
                </div>
            </div>
        </div>
    
    Tortoise SVN does not ask for user/pass and fails

    I installed tortoiseSVN and was able to do a checkout of the dirs/files that are already in the repository (I don't need to authenticate for that) When I try to commit changes I get the following error:

    Server sent unexpected return value (403 Forbidden) in response to CHECKOUT

    I am never asked to enter my user/pass for authentication.

    Tried googling it a bit, and found various mentions of this, but no definite answer. I talked with the people in charge of the SVN server on our campus, and they claim that everything is OK on the server side...

    Any help would be greatly appreciated :)

    impl Data { pub fn to_map(&self) -> HashMap<&'static str, String> { let mut map = HashMap::new(); map.insert("title", format!("{}\n{}", self.class, self.place)); map.insert("start", utils::to_utc(self.time_begin).to_rfc3339()); map.insert("end", utils::to_utc(self.time_end).to_rfc3339()); map } pub fn class(&self) -> String { self.class.to_string() } pub fn place(&self) -> String { self.place.to_string() } pub fn begin(&self) -> NaiveDateTime { self.time_begin } pub fn end(&self) -> NaiveDateTime { self.time_end } fn parse(class: &str, times: &str, places: &str) -> Vec { let mut default = String::new(); let mut map = HashMap::new(); if places.find("(").is_some() { places.split("(") .skip(1) .map(|s| s .split(")") .map(|s| s.trim()) .collect::>() ).map(|vec| (vec.get(0).unwrap_or(&"1").clone(), vec.get(1).unwrap_or(&"N/A").clone()) ).map(|(i, p)| (parse_list_uint(i), p)) .map(|(vec, p)| vec .iter() .map(|i| map.insert(i.clone() as usize, p.to_string())) .all(|_| true) ).all(|_| true); } else { default = places.to_string(); } times .split("Từ ") .skip(1) .enumerate() .map(|(i, s)| s.replace(&format!("({})", i + 1), "")) .map(|s| { s.split(':') .map(|s| s.trim().to_string()) .collect::>() }) .map(|vec| (vec[0].clone(), vec[1].clone())) .map(|(r, o)| (Data::parse_range(&r), Data::parse_wd_period(&o))) .map(|(r, d)| Data::merge_date_time(r, d)) .enumerate() .map(|(i, vec)| { vec.iter() .map(|(b, e)| Data { class: class.to_string(), time_begin: *b, time_end: *e, place: map.get(&(i+1)).unwrap_or(&default).clone(), }) .collect::>() }) .flatten() .collect() } }, skewX: { 20: 40 }, color: { 'cyan': 'orange' }, duration: 300 }); p = html._props; return expect(html._renderProps).toEqual(['borderWidth', 'borderRadius']); }); it('should not copy customProperties to _renderProps', function() { var customProperties, html; customProperties = { originX: { type: 'number', "default": 0 }, draw: function() { return {}; } }; html = new Html({ el: el, borderWidth: '20px', borderRadius: '40px', originX: 20, customProperties: customProperties }); return expect(html._renderProps).toEqual(['borderWidth', 'borderRadius']); }); it('should call _createDeltas method ->', function() { var html; html = new Html({ el: el, borderWidth: '20px', borderRadius: '40px', x: { 20: 40 }, color: { 'cyan': 'orange' } }); spyOn(html, '_createDeltas'); html._extendDefaults(); return expect(html._createDeltas).toHaveBeenCalledWith(html._addDefaults(html._o)); }); it('should parse el ->', function() { var div, html; div = document.createElement('div'); div.setAttribute('id', 'js-el'); document.body.appendChild(div); html = new Html({ el: '#js-el', borderWidth: '20px', borderRadius: '40px', x: { 20: 40 }, color: { 'cyan': 'orange' } }); html._props.el = null; html._extendDefaults(); expect(html._props.el instanceof HTMLElement).toBe(true); return expect(html._props.el).toBe(div); }); it('should save _props.el to el ->', function() { var div, html; div = document.createElement('div'); html = new Html({ el: div, borderWidth: '20px', borderRadius: '40px', x: { 20: 40 }, color: { 'cyan': 'orange' } }); return expect(html.el).toBe(div); }); return it('should use props if passed ->', function() { var html, props; props = {}; html = new Html({ el: document.createElement('div'), props: props }); return expect(html._props).toBe(props); }); }); describe('_createDeltas method ->', function() { it('should create deltas with passed object', function() { var html; html = new Html({ el: el, borderWidth: '20px', borderRadius: '40px', x: { 20: 40 }, color: { 'cyan': 'orange' } }); How to use single & multiple comment line in twig

    I'm new in twig project. I need to comment some code like // or /**/. how to use comment in twig?

        {%if role=3 %}
    <div class="col-md-6">
            <div class="form-group">
               <label class="control-label">&nbsp;</label>
               <select multiple class="form-control"  id="path_attachment" name="path_attachment[]"></select>
            </div>
    </div>
    {% else %}
    <div class="col-md-6"></div>
    {% endif %}
    
    Overwrite font: in CSS

    I have an existing web page on which there is a CSS file that I am unable to change which has the following CSS in it:

    body {
        background: none repeat scroll 0 0 #FFFFFF;
        color: #000000;
        font: 0.8em Verdana,Arial,sans-serif;
    }
    

    I am adding in an additional CSS file, and for the part of the page that its controlling I need to be able to overwrite the font size that is above, and set the size to the auto size as supplied by the browser and a different font family.

    I know about putting the !important tag on there so changing the font family hasn't been a problem, but if I don't put a size in there it strips it out when the page compiles.

    I thought I could use font-size: to override it, but I'm unclear as to how to set that to be whatever the browser has automatically.

    All help would be much appreciated! I'm a bit of a CSS novice!

    use std::collections::BTreeMap; use k8s_openapi::{api::core::v1::ConfigMap, chrono::Utc}; use super::utils; #[derive(Clone)] pub struct KubeConfigMap { pub name: String, pub namespace: String, pub data: BTreeMap, pub age: String, } impl KubeConfigMap { pub fn from_api(cm: &ConfigMap) -> Self { let data = match cm.data.as_ref() { Some(d) => d.to_owned(), _ => BTreeMap::new(), }; KubeConfigMap { name: cm.metadata.name.clone().unwrap_or_default(), namespace: cm.metadata.namespace.clone().unwrap_or_default(), age: utils::to_age(cm.metadata.creation_timestamp.as_ref(), Utc::now()), data, } } } # -*- coding: utf8 -*- def filter_event(event, happening_before): """Check if the following keys are present. These keys only show up when using the API. If fetching from the iCal, JSON, or RSS feeds it will just compare the dates """ status = True visibility = True actions = True if 'status' in event: status = event['status'] == 'upcoming' if 'visibility' in event: visibility = event['visibility'] == 'public' if 'self' in event: actions = 'announce' not in event['self']['actions'] return (status and visibility and actions and event['time'] < happening_before) Is *this* really the best way to start a second JVM from Java code?

    This is a followup to my own previous question and I'm kind of embarassed to ask this... But anyway: how would you start a second JVM from a standalone Java program in a system-independent way? And without relying on for instance an env variable like JAVA_HOME as that might point to a different JRE than the one that is currently running. I came up with the following code which actually works but feels just a little awkward:

    public static void startSecondJVM() throws Exception {
        String separator = System.getProperty("file.separator");
        String classpath = System.getProperty("java.class.path");
        String path = System.getProperty("java.home")
                    + separator + "bin" + separator + "java";
        ProcessBuilder processBuilder = 
                    new ProcessBuilder(path, "-cp", 
                    classpath, 
                    AnotherClassWithMainMethod.class.getName());
        Process process = processBuilder.start();
        process.waitFor();
    }
    

    Also, the currently running JVM might have been started with some other parameters (-D, -X..., ...) that the second JVM would not know about.

    Can I download file from URL link generated by google apps script

    Please help I'm learning google-apps-script for short time. I want to download file from remote site by url generating from data that stores in my spreadsheet.

    for example, i have 2 paremeters:

    Cell1 = val1, val2, ... valN
    Cell2 = val21, val22, ...  val2N
    

    I split string from cell data to Arrays and than generate URL. for example: http://mysite.com/files/file.val1.val22.zip Than i need to download file from this link...

    Can I do this process automaticaly ?

    // |reftest| shell-option(--enable-private-methods) skip-if(!xulRuntime.shell) async -- requires shell-options // This file was procedurally generated from the following sources: // - src/dstr-binding/ary-ptrn-elem-id-init-undef.case // - src/dstr-binding/default/cls-expr-async-private-gen-meth-dflt.template /*--- description: Destructuring initializer with an undefined value (private class expression async generator method (default parameter)) esid: sec-class-definitions-runtime-semantics-evaluation features: [class, class-methods-private, async-iteration] flags: [generated, async] info: | ClassExpression : class BindingIdentifieropt ClassTail 1. If BindingIdentifieropt is not present, let className be undefined. 2. Else, let className be StringValue of BindingIdentifier. 3. Let value be the result of ClassDefinitionEvaluation of ClassTail with argument className. [...] 14.5.14 Runtime Semantics: ClassDefinitionEvaluation 21. For each ClassElement m in order from methods a. If IsStatic of m is false, then i. Let status be the result of performing PropertyDefinitionEvaluation for m with arguments proto and false. [...] Runtime Semantics: PropertyDefinitionEvaluation AsyncGeneratorMethod : async [no LineTerminator here] * PropertyName ( UniqueFormalParameters ) { AsyncGeneratorBody } 1. Let propKey be the result of evaluating PropertyName. 2. ReturnIfAbrupt(propKey). 3. If the function code for this AsyncGeneratorMethod is strict mode code, let strict be true. Otherwise let strict be false. 4. Let scope be the running execution context's LexicalEnvironment. 5. Let closure be ! AsyncGeneratorFunctionCreate(Method, UniqueFormalParameters, AsyncGeneratorBody, scope, strict). [...] 13.3.3.6 Runtime Semantics: IteratorBindingInitialization SingleNameBinding : BindingIdentifier Initializeropt [...] 6. If Initializer is present and v is undefined, then a. Let defaultValue be the result of evaluating Initializer. b. Let v be GetValue(defaultValue). [...] 7. If environment is undefined, return PutValue(lhs, v). 8. Return InitializeReferencedBinding(lhs, v). ---*/ var callCount = 0; var C = class { async * #method([x = 23] = [undefined]) { assert.sameValue(x, 23); callCount = callCount + 1; } get method() { return this.#method; } }; new C().method().next().then(() => { assert.sameValue(callCount, 1, 'invoked exactly once'); }).then($DONE, $DONE); server_setting['port']['default'] + ') : ', end = '') setting_json[3] = str(input()) if setting_json[3] == '': setting_json[3] = server_setting['port']['default'] async with aiofiles.open('data/setting.json', 'w', encoding = 'utf8') as f: await f.write('{ "db_name" : "' + setting_json[1] + '", "db_type" : "' + setting_json[0] + '", "host" : "' + setting_json[2] + '", "port" : "' + setting_json[3] + '" }') async with aiofiles.open('data/setting.json', encoding = 'utf8') as f: setting_data = json.loads(await f.read()) db = await aiosqlite.connect(setting_data['db_name'] + '.db') db_create = {} db_create['table'] = ['doc', 'doc_cac', 'doc_his', 'rec_dis', 'rec_ban', 'rec_log', 'mbr', 'mbr_set', 'mbr_log', 'ban', 'dis', 'dis_log', 'acl', 'backlink', 'wiki_set', 'list_per', 'list_fil', 'html_fil', 'list_alarm', 'list_watch', 'list_inter'] for i in db_create['table']: try: await db.execute('select test from ' + i + ' limit 1') except: try: await db.execute('create table ' + i + '(test longtext)') except: await db.execute("alter table " + i + " add test longtext default ''") db_setup = 0 try: db_ver = await db.execute('select data from wiki_set where name = "db_ver"') db_ver = await db_ver.fetchall() if not db_ver: db_setup = 1 else: if int(version_load['main']['renew_count']) > int(db_ver[0][0]): db_setup = 1 except: db_setup = 1 if db_setup != 0: db_create['doc'] = ['title', 'data'] db_create['doc_cac'] = ['title', 'data'] db_create['doc_his'] = ['id', 'title', 'data', 'date', 'ip', 'send', 'leng', 'hide', 'type'] db_create['rec_dis'] = ['title', 'sub', 'date', 'band', 'stop', 'agree'] db_create['rec_ban'] = ['block', 'end', 'today', 'blocker', 'why', 'band'] db_create['rec_log'] = ['who', 'what', 'time'] db_create['mbr'] = ['id', 'pw', 'acl', 'date', 'email'] db_create['mbr_set'] = ['name', 'id', 'data'] db_create['mbr_log'] = ['name', 'ip', 'ua', 'today', 'sub'] db_create['ban'] = ['block', 'end', 'why', 'band', 'login'] db_create['dis'] = ['doc', 'title', 'id', 'state', 'date', 'agree'] db_create['dis_log'] = ['id', 'data', 'date', 'ip', 'block', 'top', 'code', 'doc'] db_create['acl'] = ['title', 'decu', 'dis', 'view', 'why'] db_create['backlink'] = ['title', 'link', 'type'] db_create['wiki_set'] = ['name', 'data', 'coverage'] db_create['list_per'] = ['name', 'acl'] db_create['list_fil'] = ['name', 'regex', 'sub'] db_create['html_fil'] = ['html', 'kind', 'plus'] db_create['list_alarm'] = ['name', 'data', 'date'] db_create['list_watch'] = ['user', 'title'] db_cre /* * Copyright (c), Recep Aslantas. * * MIT License (MIT), http://opensource.org/licenses/MIT * Full license can be found in the LICENSE file */ #ifndef cglmc_affine_h #define cglmc_affine_h #ifdef __cplusplus extern "C" { #endif #include "../cglm.h" CGLM_EXPORT void glmc_translate_make(mat4 m, vec3 v); CGLM_EXPORT void glmc_translate_to(mat4 m, vec3 v, mat4 dest); CGLM_EXPORT void glmc_translate(mat4 m, vec3 v); CGLM_EXPORT void glmc_translate_x(mat4 m, float to); CGLM_EXPORT void glmc_translate_y(mat4 m, float to); CGLM_EXPORT void glmc_translate_z(mat4 m, float to); CGLM_EXPORT void glmc_scale_make(mat4 m, vec3 v); CGLM_EXPORT void glmc_scale_to(mat4 m, vec3 v, mat4 dest); CGLM_EXPORT void glmc_scale(mat4 m, vec3 v); CGLM_EXPORT void glmc_scale_uni(mat4 m, float s); CGLM_EXPORT void glmc_rotate_x(mat4 m, float rad, mat4 dest); CGLM_EXPORT void glmc_rotate_y(mat4 m, float rad, mat4 dest); CGLM_EXPORT void glmc_rotate_z(mat4 m, float rad, mat4 dest); CGLM_EXPORT void glmc_rotate_make(mat4 m, float angle, vec3 axis); CGLM_EXPORT void glmc_rotate(mat4 m, float angle, vec3 axis); CGLM_EXPORT void glmc_rotate_at(mat4 m, vec3 pivot, float angle, vec3 axis); CGLM_EXPORT void glmc_rotate_atm(mat4 m, vec3 pivot, float angle, vec3 axis); CGLM_EXPORT void glmc_decompose_scalev(mat4 m, vec3 s); CGLM_EXPORT bool glmc_uniscaled(mat4 m); CGLM_EXPORT void glmc_decompose_rs(mat4 m, mat4 r, vec3 s); CGLM_EXPORT void glmc_decompose(mat4 m, vec4 t, mat4 r, vec3 s); /* affine-mat */ CGLM_EXPORT void glmc_mul(mat4 m1, mat4 m2, mat4 dest); CGLM_EXPORT void glmc_mul_rot(mat4 m1, mat4 m2, mat4 dest); CGLM_EXPORT void glmc_inv_tr(mat4 mat); #ifdef __cplusplus } #endif #endif /* cglmc_affine_h */ Run multiple insert queries against firebird database using isql

    I have requirement of inserting enormous data in table of firebird database around 40K entries. I got my scripts ready but while executing it using flameRobin, the UI just got hang forever while inserting such enormous data in one go.

    I know it would be fine if i execute my insert queries in blocks of 255 queries but i want to know if there is any bulk insert tool available for Firebird to do such entries while reading from my scripts.sql file.

    After some googling, I came across isql tool but not able to execute the scripts against it. Can someone guide me to any other tool or the proper documentation to enter such enormous data in one go?

    I have firebird version 2.5 installed on my system.

    void DrawTex_CvNormDist( const std::vector &aNormDist, const delfem2::opengl::CTexRGB &tex0, const float *R, const float *t, const float *K) { namespace lcl = ::delfem2::opengl::tex; const unsigned int nw = tex0.width; const unsigned int nh = tex0.height; assert(aNormDist.size()==nw*nh*4); ::glMatrixMode(GL_MODELVIEW); ::glPushMatrix(); float A[16]; delfem2::Mat4_AffineTrans_RotTransl( A, R, t); ::glMultMatrixf(A); // double Kinv[9]; delfem2::Inverse_Mat3(Kinv, K); // double ratio0 = 1. / Kinv[8]; float B[16]; delfem2::Mat4_Mat3(B, Kinv); float C[16]; delfem2::Transpose_Mat4(C, B); ::glMultMatrixf(C); // ::glDisable(GL_POLYGON_OFFSET_FILL); ::glEnable(GL_TEXTURE_2D); ::glBindTexture(GL_TEXTURE_2D, tex0.id_tex); ::glColor3d(1, 1, 1); ::glBegin(GL_QUADS); for (unsigned int iw = 0; iw < nw - 1; ++iw) { for (unsigned int ih = 0; ih < nh - 1; ++ih) { const float x0[3] = {float(iw)+0.5f,float(ih)+0.5f,1.f}; const float x1[3] = {float(iw)+1.5f,float(ih)+0.5f,1.f}; const float x2[3] = {float(iw)+1.5f,float(ih)+1.5f,1.f}; const float x3[3] = {float(iw)+0.5f,float(ih)+1.5f,1.f}; float Kix0[3]; MatVec3(Kix0, Kinv, x0); float Kix1[3]; MatVec3(Kix1, Kinv, x1); float Kix2[3]; MatVec3(Kix2, Kinv, x2); float Kix3[3]; MatVec3(Kix3, Kinv, x3); float ntKix0 = lcl::Dot3(aNormDist.data()+((ih + 0) * nw + (iw + 0))*4, Kix0); float ntKix1 = lcl::Dot3(aNormDist.data()+((ih + 0) * nw + (iw + 1))*4, Kix1); float ntKix2 = lcl::Dot3(aNormDist.data()+((ih + 1) * nw + (iw + 1))*4, Kix2); float ntKix3 = lcl::Dot3(aNormDist.data()+((ih + 1) * nw + (iw + 0))*4, Kix3); // std::cout << ntKix0 << " " << ntKix1 << " " << ntKix2 << " " << ntKix3 << std::endl; double z0 = -aNormDist[((ih + 0) * nw + (iw + 0))*4+3] / ntKix0; double z1 = -aNormDist[((ih + 0) * nw + (iw + 1))*4+3] / ntKix1; double z2 = -aNormDist[((ih + 1) * nw + (iw + 1))*4+3] / ntKix2; double z3 = -aNormDist[((ih + 1) * nw + (iw + 0))*4+3] / ntKix3; ::glTexCoord2d((iw + 0.5) / nw, (ih + 0.5) / nh); ::glVertex3d(z0 * (iw + 0.5), z0 * (ih + 0.5), z0); ::glTexCoord2d((iw + 1.5) / nw, (ih + 0.5) / nh); ::glVertex3d(z1 * (iw + 1.5), z1 * (ih + 0.5), z1); ::glTexCoord2d((iw + 1.5) / nw, (ih + 1.5) / nh); ::glVertex3d(z2 * (iw + 1.5), z2 * (ih + 1.5), z2); ::glTexCoord2d((iw + 0.5) / nw, (ih + 1.5) / nh); ::glVertex3d(z3 * (iw + 0.5), z3 * (ih + 1.5), z3); } } ::glEnd(); // ::glPopMatrix(); } } #endif (function() { var Html, el, h; Html = mojs.Html; h = mojs.h; el = document.createElement('div'); describe('Html ->', function() { it('should extend Thenable', function() { var html; html = new Html({ el: el }); return expect(html instanceof mojs.Thenable).toBe(true); }); describe('_extendDefaults method ->', function() { it('should copy all non-delta properties to _props', function() { var html, p; html = new Html({ el: el, borderWidth: '20px', borderRadius: '40px', y: 40, x: { 20: 40 }, skewX: { 20: 40 }, color: { 'cyan': 'orange' } }); p = html._props; expect(p['borderWidth']).toBe('20px'); expect(p['borderRadius']).toBe('40px'); expect(p['y']).toBe('40px'); expect(p['z']).toBe(0); expect(p['skewY']).toBe(0); expect(p['angleX']).toBe(0); expect(p['angleY']).toBe(0); expect(p['angleZ']).toBe(0); expect(p['scale']).toBe(1); expect(p['scaleX']).toBe(1); expect(p['scaleY']).toBe(1); expect(p['isRefreshState']).toBe(true); expect(p['isShowStart']).toBe(true); expect(p['isShowEnd']).toBe(true); expect(p['isSoftHide']).toBe(true); expect(p['isForce3d']).toBe(false); expect(html._renderProps).toEqual(['borderWidth', 'borderRadius']); return expect(html._drawProps).toEqual(['color']); }); it('should not copy tween properties _drawProps', function() { var html, p; html = new Html({ el: el, borderWidth: '20px', borderRadius: '40px', y: 40, x: { 20: 40 }, skewX: { 20: 40 }, color: { 'cyan': 'orange' }, duration: 300, timeline: { delay: 300 } }); p = html._props; return expect(html._drawProps).toEqual(['color']); }); it('should not copy customProperties _drawProps', function() { var customProperties, html, p; customProperties = { originX: { type: 'number', "default": 0 }, draw: function() { return {}; } }; html = new Html({ el: el, color: { 'cyan': 'red' }, originX: { 20: 40 }, customProperties: customProperties }); p = html._props; return expect(html._drawProps).toEqual(['color']); }); it('should not copy tween properties _renderProps', function() { var html, p; html = new Html({ el: el, borderWidth: '20px', borderRadius: '40px', y: 40, x: { 20: 40 PSQLException: The column index is out of range: 2, number of columns: 1

    The following error occured when try to query a list of email with provided email,password. Actually the subscribers_table has 10 columns with column names of email and password.

    [PSQLException: The column index is out of range: 2, number of columns: 1.]
    

    My LoginProcess Model code:

        case class LoginProcess(email:String,password:String)
    
        //error occured in this line
        implicit val getLoginProcessResult = GetResult(r => LoginProcess(r.nextString, r.nextString))
    
        def check_Login_Success_Query(email: String,password:String) = sql"select email from provisions_schema.subscribers_table where email = $email and password=$password ".as[LoginProcess]
    
        val login_Success_Query_List = check_Login_Success_Query(email_ip,password_ip).list
    
        println("login_Success_Query_List.length ->" +login_Success_Query_List.length)
    
    What is a "django backend"?

    I've been encountering quite a few django Apps mentioning 'backend', but don't exactly know what it is. Searching around google does not give much results regarding django backends in general. Could someone give an explanation?

    To be specific, take these examples:

    Actually I think the first two and the third are a bit different, what I was more unsure about was the first two: backends included in Apps.

    #pragma once namespace pumipic { /** * Distributes current and new particles across a number of processes, then rebuilds * @param[in] new_element view of ints representing new elements for each current particle (-1 for removal) * @param[in] new_process view of ints representing new processes for each current particle * @param[in] dist Distributor set up for keeping track of processes * @param[in] new_particle_elements view of ints representing new elements for new particles (-1 for removal) * @param[in] new_particle_info array of views filled with particle data */ template void CSR::migrate(kkLidView new_element, kkLidView new_process, Distributor dist, kkLidView new_particle_elements, MTVs new_particle_info) { const auto btime = prebarrier(); Kokkos::Profiling::pushRegion("csr_migrate"); Kokkos::Timer timer; // Distributor size & rank for performing migration int comm_size = dist.num_ranks(); int comm_rank; MPI_Comm_rank(dist.mpi_comm(), &comm_rank); // If serial, skip migration if (comm_size == 1) { RecordTime("CSR particle migration", timer.seconds(), btime); rebuild(new_element, new_particle_elements, new_particle_info); Kokkos::Profiling::popRegion(); return; } import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.Collections; import org.java_websocket.WebSocket; import org.java_websocket.drafts.Draft; import org.java_websocket.drafts.Draft_17; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; public class AutobahnServerTest extends WebSocketServer { private static int counter = 0; public AutobahnServerTest( int port , Draft d ) throws UnknownHostException { super( new InetSocketAddress( port ), Collections.singletonList( d ) ); } public AutobahnServerTest( InetSocketAddress address, Draft d ) { super( address, Collections.singletonList( d ) ); } @Override public void onOpen( WebSocket conn, ClientHandshake handshake ) { counter++; System.out.println( "///////////Opened connection number" + counter ); } @Override public void onClose( WebSocket conn, int code, String reason, boolean remote ) { System.out.println( "closed" ); } @Override public void onError( WebSocket conn, Exception ex ) { System.out.println( "Error:" ); ex.printStackTrace(); } @Override public void onMessage( WebSocket conn, String message ) { conn.send( message ); } @Override public void onMessage( WebSocket conn, ByteBuffer blob ) { conn.send( blob ); } public static void main( String[] args ) throws UnknownHostException { WebSocket.DEBUG = false; int port; try { port = new Integer( args[ 0 ] ); } catch ( Exception e ) { System.out.println( "No port specified. Defaulting to 9003" ); port = 9003; } new AutobahnServerTest( port, new Draft_17() ).start(); } } How to use UIPanGestureRecognizer to move object? iPhone/iPad

    There are several examples of the UIPanGestureRecognizer class. For example I have read this and I am still not able to use it...

    On the nib file that I am working on I have a UIView (white rectangle on image) that I wish to drag with that class:

    enter image description here

    and in my .m file I have placed:

    - (void)setTranslation:(CGPoint)translation inView:(UIView *)view
    {
        NSLog(@"Test to see if this method gets executed");
    }
    

    and that method does not get executed when I drag the mouse across the UIView. I have also tried placing:

    - (void)pan:(UIPanGestureRecognizer *)gesture
    {
        NSLog(@"testing");
    }
    

    And that method does not get executed either. Maybe I am wrong but I think this methods should work like the - (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event method where I just have to place that method and it will get called whenever there are touches.

    What am I doing wrong? Maybe do I have to draw a connection to that method? If so how can I do that?

    import {BoundaryElementProvider, Flex, PortalProvider, usePortal, useElementRect} from '@sanity/ui' import React, {createElement, useEffect, useMemo, useRef, useState} from 'react' import {ScrollContainer} from '@sanity/base/components' import {unstable_useDocumentValuePermissions as useDocumentValuePermissions} from '@sanity/base/hooks' import styled, {css} from 'styled-components' import {SchemaType} from '@sanity/types' import {PaneContent} from '../../../components/pane' import {usePaneLayout} from '../../../components/pane/usePaneLayout' import {useDeskTool} from '../../../contexts/deskTool' import {useDocumentPane} from '../useDocumentPane' import {DocumentPanelHeader} from './header' import {FormView} from './documentViews' import {PermissionCheckBanner} from './PermissionCheckBanner' import {ReferenceChangedBanner} from './ReferenceChangedBanner' function getSchemaType(typeName: string): SchemaType | null { const schemaMod = require('part:@sanity/base/schema') const schema = schemaMod.default || schemaMod const type = schema.get(typeName) if (!type) return null return type } interface DocumentPanelProps { footerHeight: number | null rootElement: HTMLDivElement | null } const Scroller = styled(ScrollContainer)<{$disabled: boolean}>(({$disabled}) => { if ($disabled) { return {height: '100%'} } return css` height: 100%; overflow: auto; position: relative; scroll-behavior: smooth; outline: none; ` }) export const DocumentPanel = function DocumentPanel(props: DocumentPanelProps) { const {footerHeight, rootElement} = props const { activeViewId, displayed, documentId, documentSchema, editState, value, views, ready, documentType, } = useDocumentPane() const {collapsed: layoutCollapsed} = usePaneLayout() const parentPortal = usePortal() const {features} = useDeskTool() const [headerElement, setHeaderElement] = useState(null) const headerRect = useElementRect(headerElement) const portalRef = useRef(null) const [documentScrollElement, setDocumentScrollElement] = useState(null) const requiredPermission = value._createdAt ? 'update' : 'create' const liveEdit = useMemo(() => Boolean(getSchemaType(documentType)?.liveEdit), [documentType]) const docPermissionsInput = useMemo(() => { return {...value, _id: liveEdit ? 'dummy-id' : 'drafts.dummy-id'} }, [liveEdit, value]) const [permissions, isPermissionsLoading] = useDocumentValuePermissions({ document: docPermissionsInput, permission: requiredPermission, }) const activeView = useMemo( () => views.find((view) => view.id === activeViewId) || views[0] || {type: 'form'}, [activeViewId, views] ) // Use a local portal container when split panes is supported const portalElement: HTMLElement | null = features.splitPanes ? portalRef.current || parentPortal.element : parentPortal.element Stian Thorbjørnsen (born 10 March 1982 in Gressvik), known under the stage name Staysman, is a Norwegian singer, songwriter and presenter. Background Together with Lasse Jensen, Thorbjørnsen formed the duo Staysman & Lazz, before they disbanded in 2020. The duo was discovered when they took part in a singing competition organized by the weekly magazine Se og Hør with the song "Uten sko" in 2010. In 2015, they participated in Melodi Grand Prix with his song "En goodt stekt pizza" and ended up in third place in the final. He became known to a larger audience in 2012, when he participated in season 4 of the TV3 series Paradise Hotel. He was a participant in the TV3 series "Robinsonekspedisjonen" in 2013. In 2015, he participated in the program Skal vi danse on TV 2, where he finished in second place. In 2018 and 2019, he led the question program 10 at the top on NRK. In the spring of 2021, Thorbjørnsen was part of Hver gang vi møtes on TV 2, together with the artists Arne Hurlen, Hanne Krogh, Maria Mena, Agnete Saba, Trygve Skaug and Hkeem. In 2023, he led Melodi Grand Prix 2023 together with Arian Engebø. Discography Own publications Staysvan (2014), with Katastrofe Good Vibes 2014 (2014), with Björklund and Morgan Sulele Vardafjell 2014 (2014) Bleik og sur (2014), with Katastrofe & M.M.B Et drikkehjem 2014 (2014), with Martin Tungevaag Smaker så godt (2014), with Bøbben 10 liter kaffe og hjemmebrent (2015), with Folloruss 2015 Step Brothers 2016 (2016), with Adrian Emile and Carl León ft. Morgan Sulele Baris (Staysman Remix) (2017), with Mr. Pimp-Lotion and Oral Bee Trang trikot (2018), with Boblandslaget, Vegard Harm, Svein Østvik & Emil Gukild Staysman & Lazz Albums 1998–2008 (2013) Helt sykt store hits (2014) Helt sykt Vol. 2 (2017) The Essential Staysman & Lazz (2021) Singles/EPs import AxiosLogic from '@/services/AxiosLogic.js' const labels = { namespaced: true, state: { labels: [] }, mutations: { SET_LABELS(state, data) { state.labels = data }, ADD_LABEL(state, payload) { state.labels.push(payload) }, DELETE_LABEL(state, index) { state.labels.splice(index, 1) }, RENAME_LABEL(state, payload) { let newTitle = payload.newTitle let index = payload.index state.labels[index].title = newTitle } }, actions: { loadLabels({ commit }) { AxiosLogic.getLabels() .then(res => { commit('SET_LABELS', res.data) }) .catch(error => console.log(error)) }, postLabel({ commit }, payload) { return AxiosLogic.postLabel(payload) .then(() => { commit('ADD_LABEL', payload) }) .catch(error => console.log(error)) }, deleteLabel({ commit }, payload) { return AxiosLogic.deleteLabel(payload.id) .then(() => { commit('DELETE_LABEL', payload.index) }) .catch(error => console.log(error)) }, renameLabel({ commit }, payload) { return AxiosLogic.patchLabel(payload.id, { title: payload.newTitle }) .then(() => { commit('RENAME_LABEL', payload) }) .catch(error => console.log(error)) } } } export default labels Meaning of %04X in C and how to write the same in java

    In the java project i am working on, some portion of the project was written previously by someone else in C and now i need to write the same in Java.

    There is a statement in C code for printing to a file:

    fprintf(ff, "%04X ", image[y*width+x]);
    

    Firstly i am not sure about the meaning of %04X. I think it means that if image[i] has length five or more then print only leftmost four chararacters. To do the same in Java i thought about masking the value using and operation

     image[i] & 0xFFFF
    

    Can someone please tell me the correct meaning of %04X and how to do the same in Java? Thanks.

    import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { SpringBootAngularCrudComponent } from './spring-boot-angular-crud.component'; describe('SpringBootAngularCrudComponent', () => { let component: SpringBootAngularCrudComponent; let fixture: ComponentFixture; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ SpringBootAngularCrudComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(SpringBootAngularCrudComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); SELECT data FROM two tables in MySQL

    What I have: The next structure:

    table_zero
    -> id (PRIMARY with auto increment)
    -> other

    table_1
    -> id (foreign key to table zero id)
    -> varchar(80) Example value: (aahellobbb)
    -> one_field

    table_2
    -> id (foreign key to table zero id)
    -> varchar(160) Example value: (aaececehellobbb)
    -> other_field

    What I want: Search and get an (id,varchar) array containing all matches with the LIKE '%str%' on the varchar field. For example, if I search with the "hello" string, then I should get both example values with their respective ids. These ids are always going to be different, since they are references to a PRIMARY KEY.

    What I tried: I tried with UNION ALL but it does not work with LIMITS in my example.

    from python_dwd.additionals.functions import check_parameters, retrieve_time_resolution_from_filename,\ retrieve_parameter_from_filename, retrieve_period_type_from_filename, determine_parameters from python_dwd.enumerations.period_type_enumeration import PeriodType from python_dwd.enumerations.time_resolution_enumeration import TimeResolution from python_dwd.enumerations.parameter_enumeration import Parameter def test_check_parameters(): assert check_parameters(Parameter.PRECIPITATION, TimeResolution.MINUTE_10, PeriodType.HISTORICAL) def test_retrieve_time_resolution_from_filename(): assert retrieve_time_resolution_from_filename('10minutenwerte_2019.csv') == TimeResolution.MINUTE_10 assert retrieve_time_resolution_from_filename('1minutenwerte_2019.csv') == TimeResolution.MINUTE_1 assert retrieve_time_resolution_from_filename('tageswerte__2019.csv') == TimeResolution.DAILY assert retrieve_time_resolution_from_filename('tageswerte2019.csv') == None def test_retrieve_parameter_from_filename(): assert retrieve_parameter_from_filename('bidb_!!_st_.xml', TimeResolution.HOURLY) == Parameter.SOLAR assert retrieve_parameter_from_filename('10000_historical_nieder_.txt', TimeResolution.MINUTE_1) \ == Parameter.PRECIPITATION assert retrieve_parameter_from_filename('klima_climate_kl_.csv', TimeResolution.DAILY) == Parameter.CLIMATE_SUMMARY assert retrieve_parameter_from_filename('klima_climate_kl_.csv', TimeResolution.MINUTE_1) is None def test_retrieve_period_type_from_filename(): assert retrieve_period_type_from_filename('_hist.xml') == PeriodType.HISTORICAL assert retrieve_period_type_from_filename('no_period_type') is None def test_determine_parameters(): assert determine_parameters('10minutenwerte_hist_nieder_') == (Parameter.PRECIPITATION, TimeResolution.MINUTE_10, PeriodType.HISTORICAL) from audio import Stream, AudioSettings class PhraseRecognizer(object): def __init__(self, config, audio_settings: AudioSettings): self._config = config self._audio_settings = audio_settings def get_config(self): return self._config def get_audio_settings(self) -> AudioSettings: return self._audio_settings async def recognize(self, stream: Stream, recv_callback): raise Exception('Not implemented "recognize"') class HotwordRecognizer(object): def __init__(self, config): self._config = config def get_audio_settings(self) -> AudioSettings: raise Exception('Not implemented "get_audio_settings"') def start(self): pass def is_hotword(self, raw_frames) -> bool: raise Exception('Not implemented "is_hotword"') class VADRecognizer(object): def __init__(self, config): self._config = config def get_audio_settings(self) -> AudioSettings: raise Exception('Not implemented "get_audio_settings"') def is_speech(self, raw_frames) -> bool: raise Exception('Not implemented "is_speech"') class PhraseRecognizerConfig(object): def create_phrase_recognizer(self) -> PhraseRecognizer: raise Exception('Not implemented "create_phrase_recognizer"') class HotwordRecognizerConfig(object): def create_hotword_recognizer(self) -> HotwordRecognizer: raise Exception('Not implemented "create_hotword_recognizer"') class VADRecognizerConfig(object): def create_vad_recognizer(self) -> VADRecognizer: raise Exception('Not implemented "create_vad_recognizer"') Kuei Chih-Hung (桂治洪, aka Kwei Chi Hung, Gui Zhi-Hong, Gwai Chi-hung) (20 December 1937 – 1 October 1999) was a filmmaker who worked for the Hong Kong-based Shaw Brothers Studios, directing more than 40 films throughout the late 1960s, 1970s and early 1980s. Kuei found critical and commercial success working in a variety of genres, including the hard-boiled crime drama of The Teahouse (1974) and its sequel, Big Brother Cheng (1975), wuxia film Killer Constable (1981), The Killer Snakes (1975) and Hex (1980). Kuei often depicted the poverty of the public housing system, police corruption and colonial government rule. Early life Kuei was born in Guangzhou (in the southern Chinese province of Guangdong) on 20 December 1937. Kuei's passion for cinema began as a high school student in Hong Kong, where he would cobble together makeshift shorts from a shoebox projector and discarded film stock. After graduating from high school, he studied stage production and filmmaking at Taiwan's National School of the Arts, experimenting on several 8 mm films. After writing a few film scripts for the Taiwan film industry, Kuei joined the Shaw Brothers Studio in the early 1960s. Initially hired as an assistant director on two Taiwan-shot Shaw films, Lovers' Rock (1964) and Song of Orchid Island (1965), he then lead projects in Hong Kong and an apprenticeship in Japan, where Kuei continued to work. Shaw Brothers career At the large Shaw Brothers Studio, Kuei gained a reputation as one of the most promising assistant film directors on numerous Hong Kong productions. In 1970, at the age of 34, he finally got the opportunity to direct a feature, Love Song Over the Sea. Shot in Singapore and Malaysia, the troubled production was initially suspended after the film's star Peter Chen Ho, fell ill. The original director, Shi Mashan, left due to contractual reasons, allowing Kuei to step in. Pleased with his work on this film, the studio quickly gave him a number of directorial projects, including the musical comedy, A Time for Love and The Lady Professional (1971), both starring Lily Ho. In 1973, he joined forces with the popular Shaw Brothers filmmaker, Chang Cheh, co-directing The Delinquent, an edgy action drama about a young dishwasher who falls into a life of crime. Though a collaboration between the two men, it is Kuei who is credited with the film's distinctive visual style, including the then pioneering use of on-location shoots in Hong Kong's gritty streets and public housing complexes. The film's success led to a string of early '70s hits with Kuei as the sole director, including the women-in prison exploitation flick, The Bamboo House of Dolls and the acclaimed vigilante drama, The Teahouse. He proved a versatile, imaginative filmmaker with a distinctive style that carried through to a number of diverse genres including comedy (The Bod Squad, Rat Catcher) and horror (Ghost Eyes). // Get the service name to advertise in Consul service, ok := conf["service"] if !ok { service = DefaultServiceName } if !hostnameRegex.MatchString(service) { return nil, errors.New("service name must be valid per RFC 1123 and can contain only alphanumeric characters or dashes") } if logger.IsDebug() { logger.Debug("config service set", "service", service) } // Get the additional tags to attach to the registered service name tags := conf["service_tags"] if logger.IsDebug() { logger.Debug("config service_tags set", "service_tags", tags) } // Get the service-specific address to override the use of the HA redirect address var serviceAddr *string serviceAddrStr, ok := conf["service_address"] if ok { serviceAddr = &serviceAddrStr } if logger.IsDebug() { logger.Debug("config service_address set", "service_address", serviceAddrStr) } checkTimeout := defaultCheckTimeout checkTimeoutStr, ok := conf["check_timeout"] if ok { d, err := parseutil.ParseDurationSecond(checkTimeoutStr) if err != nil { return nil, err } min, _ := durationMinusBufferDomain(d, checkMinBuffer, checkJitterFactor) if min < checkMinBuffer { return nil, fmt.Errorf("consul check_timeout must be greater than %v", min) } checkTimeout = d if logger.IsDebug() { logger.Debug("config check_timeout set", "check_timeout", d) } } // Configure the client consulConf := api.DefaultConfig() // Set MaxIdleConnsPerHost to the number of processes used in expiration.Restore consulConf.Transport.MaxIdleConnsPerHost = consts.ExpirationRestoreWorkerCount SetupSecureTLS(context.Background(), consulConf, conf, logger, false) consulConf.HttpClient = &http.Client{Transport: consulConf.Transport} client, err := api.NewClient(consulConf) if err != nil { return nil, fmt.Errorf("client setup failed: %w", err) } // Setup the backend c := &serviceRegistration{ Client: client, logger: logger, serviceName: service, serviceTags: strutil.ParseDedupLowercaseAndSortStrings(tags, ","), serviceAddress: serviceAddr, checkTimeout: checkTimeout, disableRegistration: disableRegistration, notifyActiveCh: make(chan struct{}), notifySealedCh: make(chan struct{}), notifyPerfStandbyCh: make(chan struct{}), notifyInitializedCh: make(chan struct{}), isActive: atomicB.NewBool(state.IsActive), isSealed: atomicB.NewBool(state.IsSealed), isPerfStandby: atomicB.NewBool(state.IsPerformanceStandby), isInitialized: atomicB.NewBool(state.IsInitialized), } return c, nil } func SetupSecureTLS(ctx context.Context, consulConf *api.Config, conf map[string]string, logger log.Logger, isDiagnose bool) error { if addr, ok := conf["address"]; ok { consulConf.Address = addr if logger.IsDebug() { logger.Debug("config address set", "address", addr) } Azincourt (), historically known in English as Agincourt ( ), is a commune in the Pas-de-Calais department in northern France. It is situated north-west of Saint-Pol-sur-Ternoise on the D71 road between Hesdin and Fruges. The Late Medieval Battle of Agincourt between the English and the French took place in the commune in 1415. Toponym The name is attested as Aisincurt in 1175, derived from a Germanic masculine name Aizo, Aizino and the early Northern French word curt (which meant a farm with a courtyard; derived from the Late Latin cortem). The name has no etymological link with Agincourt, Meurthe-et-Moselle (attested as Egincourt 875), which is derived separately from another Germanic male name *Ingin-. History Azincourt is known for being near the site of the battle fought on 25 October 1415 in which the army led by King Henry V of England defeated the forces led by Charles d'Albret on behalf of Charles VI of France, which has gone down in history as the Battle of Agincourt. According to M. Forrest, the French knights were so encumbered by their armour that they were exhausted even before the start of the battle. After he became king in 1509, Henry VIII is purported to have commissioned an English translation of a Life of Henry V so that he could emulate him, on the grounds that he thought that launching a campaign against France would help him to impose himself on the European stage. In 1513, Henry VIII crossed the English Channel, stopping by at Azincourt. The battle, as was the tradition, was named after a nearby castle called Azincourt. The castle has since disappeared and the settlement now known as Azincourt adopted the name in the seventeenth century. John Cassell wrote in 1857 that "the village of Azincourt itself is now a group of dirty farmhouses and wretched cottages, but where the hottest of the battle raged, between that village and the commune of Tramecourt, there still remains a wood precisely corresponding with the one in which Henry placed his ambush; and there are yet existing the foundations of the castle of Azincourt, from which the king named the field." Population Sights The original battlefield museum in the village featured model knights made out of Action Man figures. This has now been replaced by the Centre historique médiéval d'Azincourt (CHM)a more professional museum, conference centre and exhibition space incorporating laser, video, slide shows, audio commentaries, and some interactive elements. The museum building is shaped like a longbow similar to those used at the battle by archers under King Henry. Custom Validator not firing

    I realize there are lots of similar posts, however I have not found one that has worked for me unfortunately. Basically, I have an asp:customvalidator that I am trying to add to a validationgroup with other validators so that all error messages appear in the same alert. Here is the customvalidator

    <asp:TextBox runat="server" ID="txtVideo1Url"  Columns="20" Width="98%" />
    <asp:CustomValidator runat="server" ID="valURL1" ControlToValidate="txtVideo1Url" OnServerValidate="txtVideo1Url_ServerValidate" Display="None" ValidationGroup="submission" />
    

    and here is the event

        protected void txtVideo1Url_ServerValidate(object sender, ServerValidateEventArgs e)
        {
            e.IsValid = false;
            valURL1.Text = "FAIL!";
        }
    

    The event isn't firing at all and I have no idea why. Once I can get the event firing I can put some actual logic into it, lol

    UPDATE: I've noticed that I am now able to get the event firing, however the validationsummary is set to display all errors in a messagebox and this error isn't getting added to the messagebox.

    JS: "The callee (server [not server application]) is not available and disappeared." accessing window.opener

    In our (quite large and old) ASP.NET application we use a lot of pages loaded into frames, iframes, and modal dialogs (using window.showModalDialog). We are starting to see the error above quite a bit, and I can't seem to find a single rational explanation for it anywhere.

    1. Popup Blockers. Nope. We're not running them. Not even the built-in blocker.

    2. Trusted Zone. Nope. The application runs on LocalHost right now, and it's in the trusted sites list.

    3. Stray Cosmic Rays. Possible, but not probable. It's way too consistent.

    I did eventually find the error message buried on Microsoft's site in some dusty tome about retrieving automation error message information. In it, they were talking about Excel, and they said: "In this example, Microsoft Excel is the server application. Referencing a workbook object once it is destroyed (or closed) generates the error."

    That is probably as close as I've ever come to an explanation for the cause of the error, without a real, concrete explanation. Someone tried to use something after their reference to it was disposed of. Oddly, you can still see the windows on the screen. Curiously, however, this smacks suspiciously to me of the accepted answer to this.

    So here's what happens.

    • Page A is the main page.
    • PageA displays PageB in a frame. PageB is a toolbar.
    • PageA displays PageC in another frame. That's the content.
    • PageC displays PageD in a nonmodal dialog.
    • PageD, for reasons unknown to me, wants to modify the controls in PageB. It's trying to use window.opener to do that, and failing horribly.

    If someone could enlighten me as to why this is the case (the code works in FF), I'd appreciate it.

    Unable to set SCSS variable to CSS variable?

    Consider the following SCSS:

    $color-black: #000000;
    
    body {
        --color: $color-black;
    }
    

    When it is compiled with node-sass version 4.7.2, it produces following CSS:

    body {
        --color: #000000; 
    }
    

    When I compile the same SCSS with version 4.8.3 or higher, it produces following:

    body {
        --color: $color-black; 
    }
    

    What am I missing? I checked release logs, but could not found anything useful. Also, I wonder if this change is genuine why does it have only minor version change? Should it not be a major release?

    Also, what is my alternative? Should I use Interpolation?

    #ifndef POSIX_TIME_CONVERSION_HPP___ #define POSIX_TIME_CONVERSION_HPP___ /* Copyright (c) 2002-2005 CrystalClear Software, Inc. * Use, modification and distribution is subject to the * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst * $Date$ */ #include #include #include #include #include #include #include // absolute_value #include namespace boost { namespace posix_time { //! Function that converts a time_t into a ptime. inline ptime from_time_t(std::time_t t) { return ptime(gregorian::date(1970,1,1)) + seconds(t); } //! Function that converts a ptime into a time_t inline std::time_t to_time_t(ptime pt) { return (pt - ptime(gregorian::date(1970,1,1))).total_seconds(); } //! Convert a time to a tm structure truncating any fractional seconds inline std::tm to_tm(const boost::posix_time::ptime& t) { std::tm timetm = boost::gregorian::to_tm(t.date()); boost::posix_time::time_duration td = t.time_of_day(); timetm.tm_hour = td.hours(); timetm.tm_min = td.minutes(); timetm.tm_sec = td.seconds(); timetm.tm_isdst = -1; // -1 used when dst info is unknown return timetm; } //! Convert a time_duration to a tm structure truncating any fractional seconds and zeroing fields for date components inline std::tm to_tm(const boost::posix_time::time_duration& td) { std::tm timetm; std::memset(&timetm, 0, sizeof(timetm)); timetm.tm_hour = date_time::absolute_value(td.hours()); timetm.tm_min = date_time::absolute_value(td.minutes()); timetm.tm_sec = date_time::absolute_value(td.seconds()); timetm.tm_isdst = -1; // -1 used when dst info is unknown return timetm; } //! Convert a tm struct to a ptime ignoring is_dst flag inline ptime ptime_from_tm(const std::tm& timetm) { boost::gregorian::date d = boost::gregorian::date_from_tm(timetm); return ptime(d, time_duration(timetm.tm_hour, timetm.tm_min, timetm.tm_sec)); } #if defined(BOOST_HAS_FTIME) /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code, released * March 31, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /** File Name: 15.5.4.8-1.js ECMA Section: 15.5.4.8 String.prototype.split( separator ) Description: Returns an Array object into which substrings of the result of converting this object to a string have been stored. The substrings are determined by searching from left to right for occurrences of the given separator; these occurrences are not part of any substring in the returned array, but serve to divide up this string value. The separator may be a string of any length. As a special case, if the separator is the empty string, the string is split up into individual characters; the length of the result array equals the length of the string, and each substring contains one character. If the separator is not supplied, then the result array contains just one string, which is the string. Author: christine@netscape.com, pschwartau@netscape.com Date: 12 November 1997 Modified: 14 July 2002 Reason: See http://bugzilla.mozilla.org/show_bug.cgi?id=155289 ECMA-262 Ed.3 Section 15.5.4.14 The length property of the split method is 2 * */ ng rate') parser.add_argument('--weight-decay', '-wd', dest='weight_decay', action='store', default=0.0, help='weight decay') parser.add_argument('--momentum', '-mm', dest='momentum', action='store', default=0.0, help='momentum') parser.add_argument('--plateau', '-pt', dest='plateau', action='store', default=1000, help='Robbins Munro Schedule plateau length') parser.add_argument('--hidden', dest='num_hidden', action='store', default=16, help='Number of hidden units') parser.add_argument('--supernode-samples', '-ss', dest='supernode_samples', action='store', default=1, help='Number of samples to include in the supernode') parser.add_argument('--gpu-id', dest='gpu_id', action='store', default=-1, help='gpu_id') parser.add_argument('--gpu-limit', dest='gpu_limit', action='store', default=18, help='gpu_limit') parser.add_argument('--filename', dest='filename', action='store', default='temp_local', help='filename') parser.add_argument('--final-likelihood', dest='final_likelihood', action='store_const', const=True, default=False, help='compute final likelihood') parser.add_argument('--log-tour', dest='LOG_TOUR', action='store_const', const=True, default=False, help='LOG_TOUR') parser.add_argument('--name', dest='name', action='store', default=None, help='Name this run') args = parser.parse_args() return args.LOCAL, args.BASE_FOLDER, args LOCAL, BASE_FOLDER, ARGS = parse_top_level_arguments() print("Config.BASE_FOLDER=%s" % BASE_FOLDER) print("Config.LOCAL=%s" % LOCAL) DATA_FOLDER = BASE_FOLDER + 'data/' MODEL_FOLDER = BASE_FOLDER + 'data/model/' OUTPUT_FOLDER = BASE_FOLDER + 'output/' MNIST_FOLDER = BASE_FOLDER + 'py/MNIST_data/' PLOT_OUTPUT_FOLDER = BASE_FOLDER + 'plots/' SQLITE_FILE = DATA_FOLDER + 'results.db' SERVER_SQLITE_FILE = DATA_FOLDER + 'results_server.db' if LOCAL else SQLITE_FILE GPU_LIMIT = int(ARGS.gpu_limit) USE_GPU = torch.cuda.is_available() and not LOCAL LOG_TOUR = ARGS.LOG_TOUR TOUR_LENGTHS_TABLE = "TOUR_LENGTH_DISTRIBUTIONS" # These are hardcoded for the MNIST dataset WIDTH = 28 HEIGHT = 28 # These options do not work right now, we'll fix them soon PIN = False GPU_ID = int(ARGS.gpu_id) if int(ARGS.gpu_id) >= 0 else None // Token provides a parsed token kind and value. Values are provided by the // different accessor methods. type Token struct { // Kind of the Token object. kind Kind // attrs contains metadata for the following Kinds: // Name: hasSeparator bit and one of NameKind. // Scalar: one of numberValue, stringValue, literalValue. attrs uint8 // numAttrs contains metadata for numberValue: // - highest bit is whether negative or positive. // - lower bits indicate one of numDec, numHex, numOct, numFloat. numAttrs uint8 // pos provides the position of the token in the original input. pos int // raw bytes of the serialized token. // This is a subslice into the original input. raw []byte // str contains parsed string for the following: // - stringValue of Scalar kind // - numberValue of Scalar kind // - TypeName of Name kind str string } // Kind returns the token kind. func (t Token) Kind() Kind { return t.kind } // RawString returns the read value in string. func (t Token) RawString() string { return string(t.raw) } // Pos returns the token position from the input. func (t Token) Pos() int { return t.pos } // NameKind returns IdentName, TypeName or FieldNumber. // It panics if type is not Name. func (t Token) NameKind() NameKind { if t.kind == Name { return NameKind(t.attrs &^ hasSeparator) } panic(fmt.Sprintf("Token is not a Name type: %s", t.kind)) } // HasSeparator returns true if the field name is followed by the separator char // ':', else false. It panics if type is not Name. func (t Token) HasSeparator() bool { if t.kind == Name { return t.attrs&hasSeparator != 0 } panic(fmt.Sprintf("Token is not a Name type: %s", t.kind)) } // IdentName returns the value for IdentName type. func (t Token) IdentName() string { if t.kind == Name && t.attrs&uint8(IdentName) != 0 { return string(t.raw) } panic(fmt.Sprintf("Token is not an IdentName: %s:%s", t.kind, NameKind(t.attrs&^hasSeparator))) } // TypeName returns the value for TypeName type. func (t Token) TypeName() string { if t.kind == Name && t.attrs&uint8(TypeName) != 0 { return t.str } panic(fmt.Sprintf("Token is not a TypeName: %s:%s", t.kind, NameKind(t.attrs&^hasSeparator))) } // FieldNumber returns the value for FieldNumber type. It returns a // non-negative int32 value. Caller will still need to validate for the correct // field number range. func (t Token) FieldNumber() int32 { if t.kind != Name || t.attrs&uint8(FieldNumber) == 0 { panic(fmt.Sprintf("Token is not a FieldNumber: %s:%s", t.kind, NameKind(t.attrs&^hasSeparator))) } // Following should not return an error as it had already been called right // before this Token was constructed. num, _ := strconv.ParseInt(string(t.raw), 10, 32) return int32(num) } // String returns the string value for a Scalar type. func (t Token) String() (string, bool) { if t.kind != Scalar || t.attrs != stringValue { return "", false } return t.str, true } // Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/host/desktop_session_proxy.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/process/process_handle.h" #include "base/memory/shared_memory.h" #include "base/single_thread_task_runner.h" #include "ipc/ipc_channel_proxy.h" #include "ipc/ipc_message_macros.h" #include "remoting/base/capabilities.h" #include "remoting/host/chromoting_messages.h" #include "remoting/host/client_session.h" #include "remoting/host/client_session_control.h" #include "remoting/host/desktop_session_connector.h" #include "remoting/host/ipc_audio_capturer.h" #include "remoting/host/ipc_input_injector.h" #include "remoting/host/ipc_screen_controls.h" #include "remoting/host/ipc_video_frame_capturer.h" #include "remoting/proto/audio.pb.h" #include "remoting/proto/control.pb.h" #include "remoting/proto/event.pb.h" #include "third_party/webrtc/modules/desktop_capture/desktop_frame.h" #include "third_party/webrtc/modules/desktop_capture/desktop_geometry.h" #include "third_party/webrtc/modules/desktop_capture/shared_memory.h" #if defined(OS_WIN) #include "base/win/scoped_handle.h" #endif // defined(OS_WIN) const bool kReadOnly = true; const char kSendInitialResolution[] = "sendInitialResolution"; const char kRateLimitResizeRequests[] = "rateLimitResizeRequests"; namespace remoting { class DesktopSessionProxy::IpcSharedBufferCore : public base::RefCountedThreadSafe { public: IpcSharedBufferCore(int id, base::SharedMemoryHandle handle, base::ProcessHandle process, size_t size) : id_(id), #if defined(OS_WIN) shared_memory_(handle, kReadOnly, process), #else // !defined(OS_WIN) shared_memory_(handle, kReadOnly), #endif // !defined(OS_WIN) size_(size) { if (!shared_memory_.Map(size)) { LOG(ERROR) << "Failed to map a shared buffer: id=" << id #if defined(OS_WIN) << ", handle=" << handle #else << ", handle.fd=" << handle.fd #endif << ", size=" << size; } } int id() { return id_; } size_t size() { return size_; } void* memory() { return shared_memory_.memory(); } webrtc::SharedMemory::Handle handle() { #if defined(OS_WIN) return shared_memory_.handle(); #else return shared_memory_.handle().fd; #endif } private: virtual ~IpcSharedBufferCore() {} friend class base::RefCountedThreadSafe; int id_; base::SharedMemory shared_memory_; size_t size_; DISALLOW_COPY_AND_ASSIGN(IpcSharedBufferCore); }; import React from "react"; import Link from "gatsby-link"; import PropTypes from "prop-types"; import injectSheet from "react-jss"; import LazyLoad from "react-lazyload"; const styles = theme => ({ listItem: { margin: "0 0 .7em 0", transition: "height 1s", [`@media (min-width: ${theme.mediaQueryTresholds.M}px)`]: { margin: "0 0 1.5rem 0" }, [`@media (min-width: ${theme.mediaQueryTresholds.L}px)`]: { ".moving-featured &, .is-aside &": { margin: "0 0 0 0" } } }, listLink: { display: "flex", alignContent: "center", alignItems: "center", justifyContent: "flex-start", flexDirection: "row", padding: ".7em 1em .7em 1em", color: theme.navigator.colors.postsListItemLink, "@media (hover: hover)": { "&:hover": {} } }, listItemPointer: { position: "relative", flexShrink: 0, overflow: "hidden", borderRadius: "10%", width: "80px", height: "80px", margin: "0", transition: "all .5s", "& img": { width: "100%", height: "100%" }, [`@media (min-width: ${theme.mediaQueryTresholds.M}px)`]: { marginRight: ".5em", width: "90px", height: "90px" }, [`@media (min-width: ${theme.mediaQueryTresholds.L}px)`]: { marginRight: ".6em", width: "100px", height: "100px", transition: "all .3s", transitionTimingFunction: "ease", ".moving-featured &, .is-aside &": { width: "30px", height: "30px" } } }, listItemText: { margin: "0 0 0 1.5em", flexGrow: 1, display: "flex", flexDirection: "column", width: "100%", "& h1": { lineHeight: 1.15, fontWeight: 500, letterSpacing: "-0.03em", margin: 0, fontSize: `${theme.navigator.sizes.postsListItemH1Font}em`, [`@media (min-width: ${theme.mediaQueryTresholds.M}px)`]: { fontSize: `${theme.navigator.sizes.postsListItemH1Font * theme.navigator.sizes.fontIncraseForM}em` }, [`@media (min-width: ${theme.mediaQueryTresholds.L}px)`]: { fontSize: `${theme.navigator.sizes.postsListItemH1Font * theme.navigator.sizes.fontIncraseForL}em`, ".moving-featured &, .is-aside &": { fontSize: "1em", fontWeight: 400 } } }, "& h2": { lineHeight: 1.2, display: "block", fontSize: `${theme.navigator.sizes.postsListItemH2Font}em`, margin: ".3em 0 0 0", [`@media (min-width: ${theme.mediaQueryTresholds.M}px)`]: { fontSize: `${theme.navigator.sizes.postsListItemH2Font * theme.navigator.sizes.fontIncraseForM}em` }, [`@media (min-width: ${theme.mediaQueryTresholds.L}px)`]: { fontSize: `${theme.navigator.sizes.postsListItemH2Font * theme.navigator.sizes.fontIncraseForL}em`, ".moving-featured &, .is-aside &": { display: "none" } } }, [`@media (min-width: ${theme.m Articles published in the 1970s and later suggest that Debierne's results published in 1904 conflict with those reported in 1899 and 1900. Furthermore, the now-known chemistry of actinium precludes its presence as anything other than a minor constituent of Debierne's 1899 and 1900 results; in fact, the chemical properties he reported make it likely that he had, instead, accidentally identified protactinium, which would not be discovered for another fourteen years, only to have it disappear due to its hydrolysis and adsorption onto his laboratory equipment. This has led some authors to advocate that Giesel alone should be credited with the discovery. A less confrontational vision of scientific discovery is proposed by Adloff. He suggests that hindsight criticism of the early publications should be mitigated by the then nascent state of radiochemistry: highlighting the prudence of Debierne's claims in the original papers, he notes that nobody can contend that Debierne's substance did not contain actinium. Debierne, who is now considered by the vast majority of historians as the discoverer, lost interest in the element and left the topic. Giesel, on the other hand, can rightfully be credited with the first preparation of radiochemically pure actinium and with the identification of its atomic number 89. The name actinium originates from the Ancient Greek aktis, aktinos (ακτίς, ακτίνος), meaning beam or ray. Its symbol Ac is also used in abbreviations of other compounds that have nothing to do with actinium, such as acetyl, acetate and sometimes acetaldehyde. Properties Actinium is a soft, silvery-white, radioactive, metallic element. Its estimated shear modulus is similar to that of lead. Owing to its strong radioactivity, actinium glows in the dark with a pale blue light, which originates from the surrounding air ionized by the emitted energetic particles. Actinium has similar chemical properties to lanthanum and other lanthanides, and therefore these elements are difficult to separate when extracting from uranium ores. Solvent extraction and ion chromatography are commonly used for the separation. The first element of the actinides, actinium gave the set its name, much as lanthanum had done for the lanthanides. The actinides are much more diverse than the lanthanides and therefore it was not until 1945 that the most significant change to Dmitri Mendeleev's periodic table since the recognition of the lanthanides, the introduction of the actinides, was generally accepted after Glenn T. Seaborg's research on the transuranium elements (although it had been proposed as early as 1892 by British chemist Henry Bassett). React Native "onViewableItemsChanged" not working while scrolling on dynamic data

    I have a React Native FlatList. base on Documentation I used onViewableItemsChanged for getting the current showing item on the screen. but while scrolling or when scrolling stops nothing happens and I can't get the current Id. How Can I use it in correct way?

    export default class TimeLine extends Component {
    constructor(props) {
        super(props);
        this.renderTimeline = this.renderTimeline.bind(this);
        this.state = {
            timeline: [],
        };
        this.handleViewableItemsChanged = this.handleViewableItemsChanged.bind(this);
        this.viewabilityConfig = {
            itemVisiblePercentThreshold: 50,
        };
    }
    ...
    renderTimelineList(timeline_data) {
    
    
        return (
    
            <Card key={timeline_data.unique_id}>
                <CardItem style={styles.header}>
                    <Left>
                        <Icon type="MaterialIcons" name={this.timelineIcon(timeline_data.type)}/>
                        <Body>
                        <Text style={styles.header_title}>{timeline_data.title}</Text>
    
                        </Body>
                    </Left>
                </CardItem>
    
                <CardItem>
                    {this.renderTimeline(timeline_data)}
                </CardItem>
    
                <CardItem>
                    <Left>
                        <Icon small name="time" style={styles.small_font}/>
                        <Text note style={styles.small_font}>{timeline_data.release_date}</Text>
                    </Left>
                    <Right>
                        <Text note style={styles.small_font}>{timeline_data.duration}</Text>
                    </Right>
                </CardItem>
            </Card>
        );
    
    
    }
    render() {
        return (
            <Container>
                <Content>
                    <FlatList
                        key={this.state.key}
                        onViewableItemsChanged={this.handleViewableItemsChanged}
                        viewabilityConfig={this.viewabilityConfig}
                        data={this.state.timeline}
                        renderItem={({item}) => this.renderTimelineList(item)}
                    />
                </Content>
            </Container>
        );
    };
    }
    
    import numpy import mysql.connector from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import OneHotEncoder from sklearn import tree ##--------------------------Catch Data from data base-------------------------------- cnx = mysql.connector.connect(user = [type your user] , password = [type your password] , host = [type your host] , database = [type your database name] ) cur = cnx.cursor() cur.execute("SELECT Neighborhood, Area, rooms, Antiquity FROM specifications") inputData = cur.fetchall() cur.execute("SELECT Price FROM specifications") outputData = cur.fetchall() if cur: cur.close() if cnx: cnx.close() ## TestData newApartments = [['ولنجک', 120, '2','2'], ['میرداماد', 110, '2','0'], ['هروی', 200, '4','2']] for i in newApartments: ## Add newApartments to input of table inputData.append(i) Neighborhood = list() Area = list() rooms = list() Antiquity = list() for i in inputData : Neighborhood.append(i[0]) Area.append(i[1]) rooms.append(i[2]) Antiquity.append(i[3]) # Encode Neighborhood values = numpy.array(Neighborhood) # integer encode labelEncoder = LabelEncoder() integer_encoded = labelEncoder.fit_transform(values) # binary encode NeighborhoodOHE = OneHotEncoder(sparse=False) integer_encoded = integer_encoded.reshape(len(integer_encoded), 1) NeighborhoodOHE = NeighborhoodOHE.fit_transform(integer_encoded) test= Area+rooms x = numpy.column_stack((NeighborhoodOHE, Area,rooms, Antiquity)) y = outputData print(x[1]) print(len(x)) print(len(x[1])) temp = numpy.split(x, [(-1)*len(newApartments)]) x = temp[0] newApartments_enc = temp[1] # Start training and testing clf = tree.DecisionTreeClassifier() clf = clf.fit(x, y) # Encode New Apartment answer = clf.predict(newApartments_enc) for i in range(len(answer)): print("The price of Apartment in %s with %i metters Area, is approaximately %s Tomans." % (newApartments[i][0],newApartments[i][1], answer[i])) /* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ALIBABACLOUD_SMARTAG_MODEL_CREATEQOSPOLICYREQUEST_H_ #define ALIBABACLOUD_SMARTAG_MODEL_CREATEQOSPOLICYREQUEST_H_ #include #include #include #include #include namespace AlibabaCloud { namespace Smartag { namespace Model { class ALIBABACLOUD_SMARTAG_EXPORT CreateQosPolicyRequest : public RpcServiceRequest { public: CreateQosPolicyRequest(); ~CreateQosPolicyRequest(); std::vector getDpiGroupIds() const; void setDpiGroupIds(const std::vector &dpiGroupIds); long getResourceOwnerId() const; void setResourceOwnerId(long resourceOwnerId); std::string getSourcePortRange() const; void setSourcePortRange(const std::string &sourcePortRange); std::string getSourceCidr() const; void setSourceCidr(const std::string &sourceCidr); std::string getDescription() const; void setDescription(const std::string &description); std::string getStartTime() const; void setStartTime(const std::string &startTime); std::string getDestCidr() const; void setDestCidr(const std::string &destCidr); std::vector getDpiSignatureIds() const; void setDpiSignatureIds(const std::vector &dpiSignatureIds); std::string getRegionId() const; void setRegionId(const std::string ®ionId); std::string getQosId() const; void setQosId(const std::string &qosId); std::string getResourceOwnerAccount() const; void setResourceOwnerAccount(const std::string &resourceOwnerAccount); std::string getIpProtocol() const; void setIpProtocol(const std::string &ipProtocol); std::string getOwnerAccount() const; void setOwnerAccount(const std::string &ownerAccount); std::string getEndTime() const; void setEndTime(const std::string &endTime); long getOwnerId() const; void setOwnerId(long ownerId); int getPriority() const; void setPriority(int priority); std::string getDestPortRange() const; void setDestPortRange(const std::string &destPortRange); std::string getName() const; void setName(const std::string &name); private: std::vector dpiGroupIds_; long resourceOwnerId_; std::string sourcePortRange_; std::string sourceCidr_; std::string description_; std::string startTime_; std::string destCidr_; std::vector Get the list of installed packages by user in R

    How we can get the list of installed packages by user in R along with its version?

    I know about the command installed.packages() which will give information about all packages (base or non-base). But how we can get those installed by user to have something like this:

    Package    Version
    X          3.01
    Y          2.0.1
    Z          1.0.2
    

    For all user installed packages (i.e. those package you installed via install.packages("X"))

    /* * Copyright (C) 2016 Nishant Srivastava * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.nisrulz.sensey; import static com.github.nisrulz.sensey.TouchTypeDetector.SCROLL_DIR_DOWN; import static com.github.nisrulz.sensey.TouchTypeDetector.SCROLL_DIR_LEFT; import static com.github.nisrulz.sensey.TouchTypeDetector.SCROLL_DIR_RIGHT; import static com.github.nisrulz.sensey.TouchTypeDetector.SCROLL_DIR_UP; import static com.github.nisrulz.sensey.TouchTypeDetector.SWIPE_DIR_DOWN; import static com.github.nisrulz.sensey.TouchTypeDetector.SWIPE_DIR_LEFT; import static com.github.nisrulz.sensey.TouchTypeDetector.SWIPE_DIR_RIGHT; import static com.github.nisrulz.sensey.TouchTypeDetector.SWIPE_DIR_UP; import static org.mockito.Mockito.*; import android.content.Context; import android.view.MotionEvent; import com.github.nisrulz.sensey.TouchTypeDetector.TouchTypListener; import org.junit.*; import org.junit.runner.*; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; @RunWith(RobolectricTestRunner.class) public class TouchTypeDetectorTest { private TouchTypListener mockListener; private TouchTypeDetector testTouchTypeDetector; @Test public void detectNoScrollWhenEventCoorsAreEqual() { MotionEvent ev1 = MotionEvent.obtain(10, 10, 0, 50, 2, 0); MotionEvent ev2 = MotionEvent.obtain(10, 10, 0, 50, 2, 0); testTouchTypeDetector.gestureListener.onScroll(ev1, ev2, 0, 0); verifyNoMoreInteractions(mockListener); } @Test public void detectNothingForSlightlyScrollDown() { MotionEvent ev1 = MotionEvent.obtain(10, 10, 0, 0, 1, 0); MotionEvent ev2 = MotionEvent.obtain(10, 10, 0, 0, 2, 0); testTouchTypeDetector.gestureListener.onScroll(ev1, ev2, 0, 0); verifyNoMoreInteractions(mockListener); } @Test public void detectNothingForSlightlyScrollLeft() { MotionEvent ev1 = MotionEvent.obtain(10, 10, 0, 1, 0, 0); MotionEvent ev2 = MotionEvent.obtain(10, 10, 0, 2, 0, 0); testTouchTypeDetector.gestureListener.onScroll(ev1, ev2, 0, 0); verifyNoMoreInteractions(mockListener); }